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