I have am creating an app that will allow a user to pick a photo from the gallery. Once they click on the photo I am saving the uri to my room db. When I try to go back and view the photo in my app I get this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dayaramo.wearyourcloset/com.dayaramo.wearyourcloset.EditItem}: java.lang.SecurityException: No persistable permission grants found for UID 10492 and Uri content://com.android.externalstorage.documents/document/primary:DCIM/Camera/20200508_145429.jpg
I know that you are supposed to use the takePersistableUriPermissions but it seems to be ignoring that.
The code to pick and save the image uri from the gallery is
void imageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// update the preview image in the layout
pictureResult.setImageURI(selectedImageUri);
}
}
}
The code to view the photo again is
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
this.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
pictureResult.setImageURI(uri);
Is it best practice to copy the photo from the shared storage into the apps internal storage? I don’t care if the photo get’s moved or deleted which is why I just want to use the URI instead of copying it.
2
Answers
Other than perhaps the last line, the rest of that code snippet is either incorrect or unused.
Instead, call
takePersistableUriPermission()
insideonActivityResult()
, so you request durable access right away:Also, only ask for write permission if you are intending to replace the image at that
Uri
, and bear in mind that you cannot always get write access.And, as blackapps noted, you need to switch from
ACTION_GET_CONTENT
toACTION_OPEN_DOCUMENT
.For
Intent.ACTION_GET_CONTENT
you cannot take persistable permission.Use
ACTION_OPEN_DOCUMENT
instead.Take them in onActivityResult as you have been said already.