Wednesday, 5 May 2021

registerForActivityResult not working when second activity orientation changes

I am calling activity B from activity A using the ActivityResultLauncher and setting the result from activity B when the task is done. This works perfectly if orientation is not changed. The problem is when I change orientation from activity B and then setting the result, then registerForActivityResult of activity A is not called. Could someone let me know, what could be the issue?

Note: I do not face this issue if I am using startActivityForResult and onActivityResult. I changed this to ActivityResultLauncher as startActivityForResult became deprecated.

activity A sample code:

private lateinit var launcher: ActivityResultLauncher<Intent>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(layout)
    setLauncherResult()
}

private fun setLauncherResult() {
    launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            //Do operations here
        }
}

 //On button click starting activity B using launcher
 val intent = Intent(activityA, activityB)
 launcher.launch(intent)

}

activity B sample code:

//setting result
val intent = Intent()
//set intent extras
setResult(Activity.RESULT_OK, intent)
finish()


from registerForActivityResult not working when second activity orientation changes

No comments:

Post a Comment