How to store the uri of image from registerForActivityResult() and send it to another function

Viewed 446

The image i've selected from gallery disappear after the configuration changes, so i wanted to get the uri of the image so i can pass it to onSaveInstanceState but i don't know how to do so.

val selectImageFromGalleryResult = registerForActivityResult(
        ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            profileImage.setImageURI(uri)
        }
    }

    selectBtn.setOnClickListener {
        profileImage.visibility = View.VISIBLE
        selectImageFromGalleryResult.launch("image/*")
    }

If i create a global variable,

private lateinit var imageUri: Uri

i get error saying it has not been initialized if i get the value from the above function and try to send it to onSaveInstanceState

1 Answers

Uri is Parcelable itself, you can directly put it into the Bundle. To help with saving it to state, you may need to create member variable in your activity

private var profileImageUri: Uri? = null

and once you obtain Uri from ActivityResultContracts.GetContent(), then store it in profileImageUri

val selectImageFromGalleryResult = registerForActivityResult(
        ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            profileImageUri = uri
            profileImage.setImageURI(uri)
        }
    }

and save this profileImageUri in Bundle at onSaveInstanceState()

override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
    outState.putParcelable("profileImageUri", profileImageUri)
    super.onSaveInstanceState(outState, outPersistentState)
}

and to make sure on configuration change the image view load the uri, put below code in your onCreate() function

profileImageUri = savedInstanceState?.getParcelable("profileImageUri")
profileImageUri?.let {
    profileImage.setImageURI(it)
}

Additional: if you use ViewModel, it will give you more concise way. Just can create an object to save the Uri in the ViewModel and no longer need to create boilerplate code above to survive the Uri on configuration changes

Related