0

I've just been coding in kotlin for a while. I've got some problems.

It always return null data in after I click item in second activity.

first activity

btnClick.setOnClickListener { v ->
        val intent = Intent(applicationContext, NumberPickerActivity::class.java)
        startActivityForResult(intent, 777)
    }



 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    try {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 777 && resultCode == Activity.RESULT_OK) {
            val result = data?.getStringExtra("picked_product").toString()
            Toast.makeText(applicationContext, result, Toast.LENGTH_SHORT).show()
        }
    } catch (e: Exception) {
        Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
    }

}

second activity

override fun onItemClick(item: Product) {
         val intent = Intent()
         intent.putExtra("picked_product", item.price)
         setResult(Activity.RESULT_OK, intent)
         finish()
}
The Tom
  • 15
  • 1
  • 4

2 Answers2

2

Because you are expecting an Int, do this instead:

val result = data?.getIntExtra("picked_product", 0) //0 will be used in case no value in data and result is now Integer.
Neurotransmitter
  • 6,289
  • 2
  • 51
  • 38
Xenolion
  • 12,035
  • 7
  • 33
  • 48
0

The extra you put in your intent is an Integer (item.price). But you are trying to retrive a String data?.getStringExtra("picked_product").

Sinc the intent does not contain a String at the key "picked_product", it returns null.

You should try to get an Int extra :

val result = data?.getIntExtra("picked_product")

Nothing to do with your problem but it's useless to do

data?.getStringExtra("picked_product").toString()

Since it return you a String the use of toString() is useless

vincrichaud
  • 2,218
  • 17
  • 34