2

When a user presses btnOpen in the FirstFragment, it'll create an activity. When clicks btnDone in SecondActivity, it should close the activity and pass back a String to the fragment.

FirstFragment.kt

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    btnOpen.setOnClickListener {
    var someActivityResultLauncher = registerForActivityResult(
        StartActivityForResult(),
        ActivityResultCallback<ActivityResult> { result ->
            println(result.data)
        })

    val intent = Intent(context, SecondActivity::class.java)
    activityLauncher.launch(intent)
    }
}

SecondActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    btnDone.setOnClickListener{
        val intent = Intent(this@InputAmountActivity,FirstFragment::class.java)
        intent.putExtra("Total","some data")
        finish()
    }
}

I'm getting null when attempting to print result.data. How exactly do I get the value of total from SecondActivity?

Jenga
  • 149
  • 4
  • 16
  • You can use activity result launcher. This may help you https://stackoverflow.com/a/68540221/10248593 and https://developer.android.com/training/basics/intents/result – Jinal Patel Mar 12 '22 at 05:00
  • I had a long and hard look at that question you suggested this morning. It was as confusing as the documentation to me, but thanks, I think I got it now! – Jenga Mar 12 '22 at 08:37

1 Answers1

4

Right now you are creating an Intent and then just throwing it away without doing anything with it. You need to use setResult() to actually send it back to your first activity:

btnDone.setOnClickListener{
    val intent = Intent(this@InputAmountActivity,FirstFragment::class.java)
    intent.putExtra("Total","some data")
    setResult(Activity.RESULT_OK, intent)
    finish()
}
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443