Crash due to device configuration change and a variable inside `ActivityResultContract`

49 Views Asked by At

I have the following custom ActivityResultContract to allow the user to take a picture and receive the resulting image uri:

open class TakePictureActivityResultContract : ActivityResultContract<Uri, Uri?>() {

    private lateinit var imageUri: Uri

    @CallSuper
    override fun createIntent(context: Context, input: Uri): Intent {
        imageUri = input

        return Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            .putExtra(MediaStore.EXTRA_OUTPUT, input)
    }

    final override fun getSynchronousResult(
        context: Context,
        input: Uri
    ): SynchronousResult<Uri?>? = null

    @Suppress("AutoBoxing")
    final override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
        return if (resultCode == Activity.RESULT_OK) {
            imageUri
        } else {
            null
        }
    }
}

But I'm facing a crash problem due to the imageUri variable. While the user is in the camera app and rotates the device, my app might be killed in background and the value stored in imageUri is lost, leading into a crash when the camera app returns with an Activity.RESULT_OK result.

kotlin.UninitializedPropertyAccessException: lateinit property imageUri has not been initialized

What's the best way to deal with this crash without having to get rid of the imageUri variable?

0

There are 0 best solutions below