Reputation: 2836
I'm getting this exception upon calling MediaStore.createWriteRequest(contentResolver, uris)
. As in Anrdroid Q and above we have to make createWriteRequest to write on storage. So I'm trying the following code and getting the exception.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
List<Uri> uris = new ArrayList<>();
uris.add(mediaUri);
MediaStore.createWriteRequest(contentResolver, uris);
//code
}
Upvotes: 0
Views: 5670
Reputation: 121
Your Uri path is wrong that's the reason the error message is shown.
Invalid Uri Path: content://com.abc.photoapp.provider/external_files/emulated/0/Pictures/camara/1623819097267.jpg
Valid Path is : content://media/external/images/media/52703
Here, I explain the file path to delete media step by step.
Step 1:
Suppose You have a file path like this "/storage/emulated/0/tempPic/export_image.jpg"
File tempFile=new File("/storage/emulated/0/tempPic/export_image.jpg");
long mediaID=getFilePathToMediaID(tempFile.getAbsolutePath(), context);
public long getFilePathToMediaID(String songPath, Context context)
{
long id = 0;
ContentResolver cr = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String selection = MediaStore.Audio.Media.DATA;
String[] selectionArgs = {songPath};
String[] projection = {MediaStore.Audio.Media._ID};
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = cr.query(uri, projection, selection + "=?", selectionArgs, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
id = Long.parseLong(cursor.getString(idIndex));
}
}
return id;
}
Step 2:
Create media id to Uri
Uri Uri_one = ContentUris.withAppendedId( MediaStore.Images.Media.getContentUri("external"),mediaID);
// content://media/external/images/media/52703
The content Uri change according to your file type:
If Image then : MediaStore.Images.Media.getContentUri("external") If Video then : MediaStore.Video.Media.getContentUri("external")
Step 3:
Prepare and call to delete
List<Uri> uris=new ArrayList<>();
uris.add(<Add Paht : Uri_one >);
uris.add(<Add Paht : Uri_two >);
uris.add(<Add Paht : Uri_three >);
requestDeletePermission( context,uris);
enter image description here After you call the method ask permission dialog. requestDeletePermission method is return result on onActivityResult method.
The above method support android 11 (Target SDK Version 30 ) and a greater version. You do not require manage_external_storage permission for media file delete. You can use media like Video, Audio, and Images.
If you want to delete a document file so you must require manage_external_storage permission.
Upvotes: 6