Home > front end >  Kotlin - Sending data from activity back to fragment
Kotlin - Sending data from activity back to fragment

Time:03-12

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?

CodePudding user response:

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()
}
  • Related