Search code examples
androidandroid-intentandroid-imageandroid-fileandroid-storage

Android Retrieve Image by Intent Uri Failed: "has no access to content..."


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.


Solution

  • 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.