1

I use Intent to pick a photo from gallery:

binding.pickPhotoButton.setOnClickListener {
    val intent = Intent(Intent.ACTION_PICK)

    intent.type = "image/*"

    startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO)
}

And save the image uri using SharedPreferences:

object DataStore {
    fun saveImage(context: Context, imageName: String, imageUri: Uri) {
        val sharedPreferences = context.getSharedPreferences("images", Context.MODE_PRIVATE)

        sharedPreferences.edit {
            putString(imageName, imageUri.toString())
        }
    }

    fun getImageUri(context: Context, imageName: String): Uri? {
        val sharedPreferences = context.getSharedPreferences("images", Context.MODE_PRIVATE)
        val uriString = sharedPreferences.getString(imageName, "")

        return if (uriString!!.isEmpty()) null else uriString.toUri()
    }
}

Saving has no problem, but when I retrieve it and convert to Bitmap (to set it with ImageView):

val inputStream = imageView.context.contentResolver.openInputStream(uri)

inputStream.use {
    val bitmap = BitmapFactory.decodeStream(it)

    imageView.setImageBitmap(bitmap)
}

I got this error: has no access to content://media/external/images/media/690726. Any help will be appreciated.

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • you decode inputstream in onActivityResult. looks fine. where do you have `val bitmap = BitmapFactory.decodeStream(it)`. uris valid for lifetime of your component activity or fragment where you access it – Raghunandan Feb 10 '21 at 05:56
  • `uris valid for lifetime of your component activity or fragment where you access it` sounds the point, I got that error when I restart the app. So that means I have to create a copy of the image file into somewhere, then I can retrieve it, right? – Sam Chen Feb 10 '21 at 06:05
  • 1
    https://commonsware.com/blog/2016/08/10/uri-access-lifetime-shorter-than-you-might-think.html. I guess you need to get the uri by picking the image again or create a local copy – Raghunandan Feb 10 '21 at 06:07

2 Answers2

1

The read permission for the uri has gone after restart of your app or if you use the uri in another activity.

But there is a solution.

Instead of ACTION_PICK use ACTION_OPEN_DOCUMENT and take persistable uri permission for the obtained uri in onActivityResult().

blackapps
  • 8,011
  • 2
  • 11
  • 25
0

Ok, searched and experimented a lot, here is the solution:

Just use Intent.ACTION_OPEN_DOCUMENT, that's enough. No need takePersistableUriPermission().


One more interesting finding: takePersistableUriPermission() doesn't work for Intent.ACTION_PICK and Intent.ACTION_GET_CONTENT. Which is too bad, because ACTION_PICK lanuches the gallery app, provides a better ui look, while ACTION_OPEN_DOCUMENT and ACTION_GET_CONTENT launches the native file explorer app.

Sam Chen
  • 7,597
  • 2
  • 40
  • 73