'Standardize Uri between Camera and Gallery Intent Android

I'm trying to retrieve URI from gallery and camera in one place (as record in Room database), therefore i need to standardize the access between them. I get it done for the camera by create a file and then retrieve its URI. The URI looks like this:

// first URI
content://media/external_primary/images/media/45

It works and i can retrieve the image based on that URI after reopening the app. Here is the code for camera

private val launcherIntentCamera = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            val bitmap = result?.data?.extras?.get("data") as Bitmap
            val uri = savePhotoToExternalStorage(
                requireActivity().contentResolver,
                UUID.randomUUID().toString(),
                bitmap
            )
            uri?.let {
                viewModel.updateProfilePic(it.toString())
            }
        }
    }

    private fun startTakePhoto() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        launcherIntentCamera.launch(intent)
    }

And then i try for gallery intent and what i receive is this:

// second URI
content://com.android.providers.media.documents/document/image%3A44

Based on what i observe, this URI is temporary. And when i try to retrieve it after reopening the app, it doesnt work. This is my code

private val launcherIntentGallery = registerForActivityResult(
    ActivityResultContracts.GetContent()
) { uri ->
    viewModel.updateProfilePic(uri.toString())
}

    private fun startGallery() {
        requireActivity().intent.type = "image/*"
        launcherIntentGallery.launch("image/*")
    }

Is there any solution to convert the second URI to the format of first URI so i could retrieve the image when reopening the app?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source