0

I can choose image from gallery and save it's Uri path to room db in fragment 1.
While the app is still running, it's ok to get the image Uri and show it in fragment 2.

Problem
After close the app and restart it, fragment 2 will crash.

I found below post looks better to solve permission issue.
But I'm not sure how to implement it in onActivityResult (original answer is in Java).
https://stackoverflow.com/a/29588566/16430096

Below is my onActiviyResult code

    var selectedImage: Uri? = null


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == IMAGE_PICK_CODE && resultCode == Activity.RESULT_OK) {
            selectedImage = data?.data
            imageView.setImageURI(selectedImage)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val takeFlags = data?.flags?.and(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val resolver = activity?.contentResolver

            //TODO: What should I do here?
        }
    }
Justin
  • 91
  • 2
  • 6

1 Answers1

0

I found the solution from below post.
https://stackoverflow.com/a/36182357/16430096

There's no need to change onActivityResult, just use Intent.ACTION_OPEN_DOCUMENT like below.
Like the post describe, Intent.ACTION_OPEN_DOCUMENT provide longer permission even after the app is closed.

Using Intent.ACTION_PICK will only get temporary permission which will lead to SecurityException after restart the app.

private fun pickImageFromGallery() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
    intent.type = "image/*"
    if (intent.resolveActivity(requireActivity().packageManager) != null) {
        startActivityForResult(Intent.createChooser(intent, "select file"), IMAGE_PICK_CODE)
    }
}
Justin
  • 91
  • 2
  • 6