kotlinandroid-intent

In Kotlin, why using getIntExtra gives me "defaultValue" while I already gave it a value?


I want to pass some numbers between two activities by using an intent.The code is like this:

//This is the first activity, it has a button.Clicking the button will start the secondactivity and pass a number
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
...
        val binding=ActivityMainBinding.inflate(layoutInflater)
        binding.button.setOnClickListener{
            val intent=Intent(this,SecondActivity::class.java)
            intent.putExtra("plus",1)
            startActivity(intent)
        }
    }
}
class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
...
        val plus = intent.getIntExtra("a")//Here comes error:No value passed for parameter 'defaultValue'
    }
}type here

Why is it??

It is Ok to pass a String, just Int is not OK.


Solution

  • In order to use getIntExtra() function from Intent class you should provide two values:

    In your case you should call the function like:

    val plus = intent.getIntExtra("a", -1)
    

    Where -1 in this case is the default value which will be returned if no extra is sent via the intent with the given key.

    P.S. Keep in mind that you should use the same key in both activities. In your current example you are sending an extra with plus as a name in MainActivity and retrieving the value in SecondActivity using name: a.