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.