Storage Access Framework how delete file in subfolder

476 views Asked by At

Which day I struggle with the problem and have already read the entire Internet. I'm using the Storage Access Framework but can't delete a file in a subdirectory.

There is a folder on the memory card (/storage/1B15-0D11/Data). I am asking the user for permissions on this folder:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 999);

public void onActivityResult(int requestCode, int resultCode,
                         Intent resultData) {
 if (resultCode == Activity.RESULT_OK) {
    if (requestCode == 999) {
        if (resultData != null) {
            Uri treeUri=resultData.getData();
            //Log.d(TAG, "SELECT_DIR_REQUEST_CODE resultData = " + resultData);
            getContentResolver().takePersistableUriPermission(treeUri, (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));

Structure of this folder:

Data->Data1->Data2->file.txt

I know that there is a file (file.txt) on the /storage/1B15-0D11/Data/Data1/Data2 path.

But I don’t know how to remove it without going through all the subfolders.

Can be removed like this:

List<UriPermission> permissions = getContentResolver().getPersistedUriPermissions();
if (permissions != null && permissions.size() > 0) {
   DocumentFile dir = DocumentFile.fromTreeUri(this, permissions.get(0).getUri());
   DocumentFile dir2 = dir.findFile("Data1");
   DocumentFile dir3 = dir2.findFile("Data2");
   DocumentFile file = dir3.findFile("file.txt");
   if (file != null) {file.delete();}
}

It works. But that's not exactly what I need.

I have a file path in the form "/storage/1B15-0D11/Data/Data1/Data2/file.txt". How can I remove it without going through all the subfolders?

Tried like this. But that doesn't work. It turns out not the correct line URI.

DocumentFile dir = DocumentFile.fromTreeUri(this, Uri.parse("content://com.android.externalstorage.documents/tree/1B15-0D11%3AData%2FDat1%2FDat2"));
DocumentFile file = dir.findFile("text.txt"); //return null


                
2

There are 2 answers

0
J. M. On

Easier to just add the findFile to delete.

if (dir3.findFile("file.txt") !=
null) {
dir3.findFile("file.txt").delete();}
0
Dev4Life On

Try this.

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();
            }
        }
    }