How to delete files with DocumentFile in Android Q?

856 views Asked by At

Method for deleting file with document uri

private void getDocumentUri(Uri mediaUri){
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && getActivity() != null) {
                Uri documentUri = MediaStore.getDocumentUri(getActivity(), mediaUri);
                if (documentUri != null) {
                    Log.d(TAG,"getDocumentUri: "+documentUri);
                    DocumentFile documentFile = DocumentFile.fromSingleUri(getActivity(), documentUri);
                    if (documentFile != null) {
                        Log.d(TAG, "getDocumentUri documentFile not null: " + documentFile);
                        if (documentFile.delete()) {
                            Log.i(TAG, "getDocumentUri Delete successful");
                        } else {
                            Log.i(TAG, "getDocumentUri Delete unsuccessful");
                        }
                    }
                }
            }
        }catch(Exception e){
            Log.e(TAG,"getDocumentUri error: " + e);
        }
}

Logcat error

SecurityException: The app is not given any access to the document under path /storage/emulated/0/test/song.mp3 with permissions granted in [UriPermission {uri=content://com.android.externalstorage.documents/tree/primary%3AMusic, modeFlags=3, persistedTime=1601203263354}]

Weird thing is that for some files this works and for some it gives this error and all audio files are in the same place on the internal storage.

EDIT

mediaUri's value is obtained with ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));

Also the files i'm trying to delete are not created by my app

1

There are 1 answers

0
Dev4Life On

Try this method. You need to take the persistable uri permission using SAF of the parent folder, then pass the uri & name of the file to delete. (I have a model class to handle both.)

public void deleteAPI29(ArrayList<Media> mediaList) {
        Uri persistedUri = getContentResolver().getPersistedUriPermissions().get(0).getUri();
        DocumentFile documentFile = DocumentFile.fromTreeUri(this, persistedUri);
        for (int i = 0; i < mediaList.size(); i++) {
            File file = new File(mediaList.get(i).getPath());
            DocumentFile nextDocument = documentFile.findFile(file.getName());
            try {
                DocumentsContract.deleteDocument(getContentResolver(), nextDocument.getUri());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }