Can't write to SD card even after granting uri permission

I was trying to find a way to write data on the SD card for the past 2 weeks and finally today I understood what I'm supposed to be doing and I did that. And it actually worked and I could delete a file; but the EXACT same code isn't working anymore.

Here's my code:

 //granting permission
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQ_CODE);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_CODE && resultCode == Activity.RESULT_OK){
        Uri treeUri = data.getData();
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
        grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        App.editor.putString("uri",treeUri.toString()).apply();
    }
}
//MY DELETE VOID
public static boolean deleteFile(Context context, File f){
    if (isOnInternal(f)){
        return f.delete();
    }else{
        String tp = f.getAbsolutePath().replace(getsdpath(),"").substring(1);
        Uri uri = Uri.parse(App.preferences.getString("uri","null"));
        DocumentFile pickedDir = DocumentFile.fromTreeUri(context, uri);
        context.grantUriPermission(context.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        uri = uri.buildUpon().appendPath(tp).build();
        uri = uri.buildUpon().path(uri.getPath().replace("tree","document")).build();
        uri = uri.buildUpon().path(uri.getPath().replace(":/",":")).build();
        Log.e("PPP",uri.toString());
        return DocumentFile.fromSingleUri(context,uri).delete();
    }
}

I'm well aware that I'm not using the conventional way here but this worked and I was keen on keeping it this way.

I'd be glad to present any more info if there's anyone who can help and I'd appreciate any help.

UPDATE After some tests, I found out that when I want to check wether the file that my Uri refers to does actually exist, using file.exists(), it returns false.

728x90

0 Answers Can't write to SD card even after granting uri permission