androidkotlinandroid-activityonactivityresultstartactivityforresult

startActivityForResult putExtras being recieved as NULL


Hi I am creating a SideActivity to gather some results and pass them back to Main Activity. However, the two strings value from the putextra are NULL rather than the string "20" and the jamSize "medium". Is there a way of passing the data properly?

Here in my Main Activity I have a setOnClickListener and a onActivityResult function.

jamButton.setOnClickListener {
           var intent = Intent(this@MainActivity, SideActivity::class.java)
           intent.putExtra("jamName", "raspberry")
           intent.putExtra("jamPrice", "12.00")
           startActivityForResult(intent, 1) // passing request code value 1

       }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       super.onActivityResult(requestCode, resultCode, data)
       if(resultCode == RESULT_OK) {
           val jamPrice:String = intent.getStringExtra("jamPrice").toString()
           val jamSize:String = intent.getStringExtra("jamSize").toString()
           val newJam = DataModel("Jam", "$jamSize", "$jamPrice")
           list.add(0, newJam)
           jamAdapter.notifyItemInserted(0)
       } 
   }

Here is my Second Activity

completeBtn.setOnClickListener {
           val jamPrice: String = textView2.text.toString()
           val jamSize: String = textView3.text.toString()
           
           val intent = Intent(this@SideActivity, MainActivity::class.java) 

           intent.putExtra("jamPrice", "20.00")
           intent.putExtra("jamSize", jamSize)
           setResult(Activity.RESULT_OK, intent)
           finish()
       }

Solution

  • In your onActivityResult don't use this :

     val jamPrice:String = intent.getStringExtra("jamPrice").toString()
    

    because the intent variable is the Intent of the activity instead use :

    val jamPrice: String = data?.getStringExtra("jamPrice").toString()