How to list subfolder content when using Android DocumentFile API

424 Views Asked by At

I'm trying to switch to the DocumentFile API as Android doesn't allow using File API anymore...

When I select a folder, it returned URI is

content://com.android.externalstorage.documents/tree/primary%3AMedia%2FCamera%2FFreeTime

Now I'm calling

 DocumentFile.fromTreeUri(this, uri)

to get the content of the folder. I want to keep a list of all the subfolders within

The 1st subfolder I found has the following URI

content://com.android.externalstorage.documents/tree/primary%3AMedia%2FCamera%2FFreeTime/document/primary%3AMedia%2FCamera%2FFreeTime%2F11

I need to save it so later on I can check the files within that folder

The problem is that when I try to call

 DocumentFile.fromTreeUri(this, uri)

on this subfolder uri it returns a DocumentFile matching the parent folder of this subfolder

content://com.android.externalstorage.documents/tree/primary%3AMedia%2FCamera%2FFreeTime

How can I save the subfolder uri here so I can later on list this subfolder files?

1

There are 1 best solutions below

12
blackapps On

How can I save the subfolder uri here so I can later on list this subfolder files?

Two things.

First: take persistable uri permission on the folder choosen by the user.

Second: a subfolder uri as you save it is no tree uri and hence you cannot create a DocumentFile with .fromTreeUri().

Instead use:

 .fromSingleUri().