mdatsev
mdatsev

Reputation: 3879

How to read file content using document id

I'm requesting a directory tree from a user and I want to read all files. I'm then using something similar to this to traverse all the files. I want to then read the files (specifically create InputStreams). I tried to find a way to use COLUMN_DOCUMENT_ID and the various open file methods but they either require Uri or filepath and I can't find a way to get one from the document id. I found this method which seems like it would work for me, but it's on an abstract class and I couldn't find an implementation for the android file system. Is there a standard way to do this? I'm probably missing something obvious.

Upvotes: 1

Views: 642

Answers (1)

Pizza and Coke
Pizza and Coke

Reputation: 123

I ran into this and worked out the following way of doing it.

buildDocumentUriUsingTree() does this.

When the user chooses a directory, with SAF storage picker, the URI for that directory is returned in onActivityResult. You will need to take persistable permission on that URI, like this:

getContentResolver().takePersistableUriPermission(theSafReturnedTreeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

You can store the String returned by theSafReturnedTreeUri.toString() in order to reconstruct that URI anytime using:

Uri.parse(Uri.decode(theString));

When you want to access a file under that directory, use buildDocumentUriUsingTree, passing it theSafReturnedTreeUri and the Document ID returned when using ContentResolver to query for COLUMN_DOCUMENT_ID.

Uri myFileUri = DocumentsContract.buildDocumentUriUsingTree(theSafReturnedTreeUri, theDocIdQueriedForWithContentResolver);

That gives you a working URI for the file that you should be able to use with ContentResolver.openInputStream.

Upvotes: 1

Related Questions