Home > Net >  Files not being deleted in android 11 using MediaStore.createDeleteRequest()
Files not being deleted in android 11 using MediaStore.createDeleteRequest()

Time:12-19

I am trying to delete audio recordings that I created before Re-installing my app. I'm using MediaStore.createDeleteRequest() and it successfully shows me a dialog box to ask for permission to delete the files, but when I click "Allow" it doesn't delete the files.

My Audio Recordings are stored in "storage/emulated/0/MUSIC/Wear Voice Recorder/"

This is my code :

public void onClick(View v) {
    List<Uri> uris = new ArrayList<>();
    for (Recordings rec : selectionList) {
        String date = rec.getRecordingDate();
        SimpleDateFormat original = new SimpleDateFormat("d MMM yy, hh:mm:ss a");
        SimpleDateFormat target = new SimpleDateFormat("yyyyMMdd_HHmmss");
        try {
            tempDate = original.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String fileName = rec.getRecordingName()   "_W_"   target.format(tempDate)   ".mp3";

        File directory = Environment.getExternalStorageDirectory();
        file = new File(directory   File.separator   Environment.DIRECTORY_MUSIC   File.separator   "Wear Voice Recorder");
        File[] list = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".mp3");
            }
        });


        for (File mediaFile : list) {
            if (mediaFile.getName().equals(fileName)) {
                arrList.remove(rec);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {


                  long mediaID = getFilePathToMediaID(mediaFile.getPath(), RecordingsListActivity.this);
                  Uri Uri_one =ContentUris.withAppendedId(MediaStore.Audio.Media.getContentUri("internal"), mediaID);
                  uris.add(Uri_one);


                }
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                    try {
                        mediaFile.delete();
                    } catch (Exception e) {
                        Toast.makeText(RecordingsListActivity.this, "Recording Not Found", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
       requestDeletePermission(RecordingsListActivity.this, uris);
        System.out.println(uris "");
    }
    adapter.notifyDataSetChanged();
    endSelectionMode();
}
@RequiresApi(api = Build.VERSION_CODES.R)
private void requestDeletePermission(Context context, List<Uri> uri_one) {
    PendingIntent pi = MediaStore.createDeleteRequest(context.getContentResolver(), uri_one);
    try {
        startIntentSenderForResult(pi.getIntentSender(), REQUEST_PERM_DELETE, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}
private long getFilePathToMediaID(String path, Context context) {
    long id = 0;
    ContentResolver cr = context.getContentResolver();

    Uri uri = MediaStore.Files.getContentUri("internal");
    String selection = MediaStore.Audio.Media.DATA;
    String[] selectionArgs = {path};
    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;

}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case REQUEST_PERM_DELETE:
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(RecordingsListActivity.this, "Deleted successfully!", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(RecordingsListActivity.this, "Failed to delete!", Toast.LENGTH_SHORT).show();
            }
            break;

    }
}


I don't really know much about MediaStore, this is my first app and it's so frustrating to ask for permission to delete files that my app created before I uninstalled and re-installed.

I think there's something wrong with the URI, when I print the URI of different files, the URIs are the same.

It does show me the dialog box to delete the files and it also shows a toast saying "Deleted Successfully!" but the files are still there.

CodePudding user response:

Uri uri = MediaStore.Files.getContentUri("internal");

Try:

 Uri uri = MediaStore.Video.Media.getContentUri("internal");

But probably you should change "internal" to MediaStore.VOLUME_EXTERNAL too.

  • Related