Search code examples
androidandroid-sdcardfilewriterstorage-access-framework

Convert file PATH to TreeUri (Storage Access Framework)


In my application of image gallery I use media content provider image to inflate recycler view . On long press on an image, I give user option to rename that image file. So I have complete file path (Ex:- /storage/sdcard1/DCIM/100ANDRO/ak.jpg ) for each image in recycler view. Then I want to rename that file.

Now the issue is that as the file path provided is that of External SD Card, and for Android 5 & up, SAF(Storage Access Framework) is required to write a file.

So generally we use this code for renaming a file using SAF:-

public void onActivityResult(int requestCode, int resultCode, Intent resultData){
    if (resultCode == RESULT_OK) {
        Uri treeUri = resultData.getData();
        getContentResolver().takePersistableUriPermission(treeUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION |
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
        DocumentFile newFIle = pickedDir.createFile("text/plain","MyFile")
        // or rename as
        pickedDir.renameTo("fdtd.jpg");
    } else {
        Log.d("test","NOt OK RESULT");
    }
}

But that is in the case when we know the TreeUri. Here in my case I know fle path and hence want to convert that into TreeUri.


Solution

  • To convert file path to uri use this:-

    DocumentFile fileuri = DocumentFile.fromFile(new File(filepath));
    

    Then you can perform delete,rename operations on this fileuri.