chris_z13
chris_z13

Reputation: 21

How to get child's DocumentFile from Document Uri

Assume the following folder structure:

- root
-- Android
-- Downloads
-- ....
-- Test
--- Example
---- Dir1

Given the Uri listed below, how can I get the DocumentFile for the directory located at the /Test/Example path, where Test and Example are dynamically chosen directories?

Uri uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3ATest%2FExample");
DocumentFile f = DocumentFile.fromTreeUri(context, uri);
f.findFile(context, "Dir1"); // Returns null, because the document file is for the primary storage directory
f.findFile(context, "Test"); // Returns the document file for /Test

I need the DocumentFile for the /Test/Example directory, because I need to further iterate down the tree and find/check for the existence of additional directories, e.g. /Test/Example/Dir1/Dir2/test.txt, but I do not know before run time what the names of the directories are.

Upvotes: 2

Views: 1105

Answers (1)

Kasdonchu
Kasdonchu

Reputation: 448

You can still get down the tree one directory at a time:

DocumentFile rootDir = DocumentFile.fromTreeUri(context, uri);
if (rootDir != null) {
    DocumentFile testDir = rootDir.findFile(context, "Test");
    if (testDir != null) {
        DocumentFile exampleDir = testDir.findFile(context, "Example");
    }
}

Of course, there's probably a more elegant way to do this depending on how you get the names of the runtime-created directories.

Upvotes: 1

Related Questions