Search code examples
androidkotlinandroid-roompicasso

Save image path from gallery to Room DB, then load with Picasso not working


I've tried various solutions on SO for this problem, but so far not one of them has worked :/

I'm letting users pick a photo from a gallery, have the app display a preview, save the image with a caption to a Room DB and then display multiple images in a RecyclerView using Google's Material Design Card Views.

Picking an image and showing it in the preview is not a problem. But displaying the images in the RecyclerView using Picasso is not working. It only shows my error image (broken image vector).

The following code is used to pick an image from the gallery and display the preview image:

private fun choosePicture() {
    var chooseFile = Intent(Intent.ACTION_GET_CONTENT)
    chooseFile.type = MIME_TYPE_IMAGE
    chooseFile = Intent.createChooser(chooseFile, resources.getString(R.string.choose_file))
    startActivityForResult(chooseFile, PICK_FILE_RESULT_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when (requestCode) {
        PICK_FILE_RESULT_CODE -> if (resultCode == -1) {
            data!!.data?.let { returnUri ->
                loadPicture(returnUri)
                binding.constraintLayout.visibility = View.VISIBLE
                viewModel.imagePath.value = returnUri
            }
        }
    }
}

private fun loadPicture(uri: Uri) {
    Picasso.get()
        .load(uri)
        .error(R.drawable.ic_broken_image_gray_24dp)
        .into(binding.placeImage)
}

In my ViewHolder I'm using the following code to display the image (image path saved in Room DB as String):

fun bind(location: Location) {
    textViewLocationName.text = location.name
    Picasso.get()
        .load(Uri.parse(location.imagePath!!))
        .error(R.drawable.ic_broken_image_gray_24dp)
        .into(imageViewLocation)
}

When debugging the URI looks like this: content://com.android.providers.media.documents/document/image%3A4569

Is there some kind of formatting issue with the URI? Or is there another problem?

Thanks!


Solution

  • Just in case anyone else has this problem, here's my solution:

    1. Change the intent from ACTION_GET_CONTENT to ACTION_OPEN_DOCUMENT

    2. Set the following flags for the intent: chooseFile.flags = (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)

    3. In onActivityResult use the following line of code before using the URI for anything else: context?.contentResolver?.takePersistableUriPermission(returnUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)