Search code examples
androidandroid-5.0-lollipop

How to get the real path with ACTION_OPEN_DOCUMENT_TREE Intent?


My app downloads and unzips a file in a specific folder:

output = new FileOutputStream(realpath, true);
output.write(buffer, 0, bytesRead);

ZipFile zipFile = new ZipFile(realpath);

With the new introduced ACTION_OPEN_DOCUMENT_TREE Intent, I would like to offer the user to choose that folder.

When testing the values received in my onActivityResult, I get a Path like /tree/primary:mynewfolder, which is not the physical real path like /sdcard/mynewfolder.

Uri treeUri = data.getData();
String sPath = treeUri.getPath();
Log.v("Path from Tree ", sPath);

My unzip method need the real path:

ZipFile zipFile = new ZipFile(realpath);

How do I get the real path like /sdcard/mynewfolder from the provided URI in Lollipop (API 21 & 22)?


Solution

  • Process of getting real Path from URI is same as before, but with a little addition:

    Uri uri = data.getData();
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri, 
                            DocumentsContract.getTreeDocumentId(uri));
    String path = getPath(this, docUri);
    

    The gist of getPath() method with intermediate methods can be found here: getPath()