2

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.

Kasdonchu
  • 388
  • 3
  • 7
chris_z13
  • 21
  • 2
  • I recommend that you update your question with a [mcve], showing how you are getting this `Uri`, how you are using `fromTreeUri()`, and what you mean by "but that returns the DocumentFile for the primary storage directory". – CommonsWare Mar 05 '20 at 17:34

1 Answers1

1

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.

Kasdonchu
  • 388
  • 3
  • 7
  • Do not use the `DocumentFile.findFile`. It's too slooow. Try it call 100x. – t0m May 06 '21 at 16:29
  • @t0m It _is_ slow, you're right about that. But if for some reason you're forced to work with `DocumentFile`, then I don't know a better way to find a file. If you do, I'd be genuinely interested to read about it. – Kasdonchu May 07 '21 at 17:17
  • I am solving the same problem now. – t0m May 08 '21 at 12:56
  • Try using `DocumentFile.child` it's a non-static public method. – Alex Rintt May 23 '22 at 00:45