Belphegor
Belphegor

Reputation: 1843

Android: How to handle onActivityResult if it's overridden in multiple activitys?

In one activity called A, it has startActivityForResult(), this activity is to just open up my photo gallery and choose an image. In the same activity A, it override onActivityResult to grab the selected image.

However, I have another activity called B which happens to have onActivityResult overridden as well and it seems that activity B consumes that result and due to this issue activity A never gets the result.

Is there anything I can do to have the result go to activity A and not activity B without removing the onActivityResult in B?

Upvotes: 0

Views: 278

Answers (1)

Entreco
Entreco

Reputation: 12900

requestCode is exactly introduced for this reason. You always need to pass a requestCode when starting an activity for result:

val selectImageIntent = /* some intent to select an image */
startActivityForResult(selectImageIntent, REQUEST_CODE_SELECTED_IMAGE)

And you can use that to determine if this result is for you:

private val REQUEST_CODE_SELECTED_IMAGE = 1000 
private val REQUEST_CODE_CAMERA = 2000 

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    
    if(requestCode == REQUEST_CODE_SELECTED_IMAGE){
        // Handle the result of REQUEST_CODE_SELECTED_IMAGE
    } else {
        // Let another activity handle the result
        super.onActivityResult(requestCode, resultCode, data)
    }
}

Upvotes: 1

Related Questions