Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

listFiles() nullpointerexception when called

I’m calling listFiles() with read and write permissions granted; on Android 11 but it gives a NullPointerException error even tho the path is correct (I got the path from a ActivityResultContracts.OpenDocumentTree() Activity) and stored as variable like so folderPath = it.path

var mydir = File(folderPath)
files = mydir.listFiles()!!

it results in NullPointerException still even tho mydir is printed correctly, example:

/tree/primary:SHAREit Lite/pictures

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I got the path from a ActivityResultContracts.OpenDocumentTree() Activity

Then you are not dealing with the filesystem. You are using the Storage Access Framework, which is an abstraction around a lot of different possible places for content to be stored. But this means that you need to stop using File, because the content may not be on the filesystem, and a Uri is not a filesystem path.

Instead, use DocumentFile.fromTreeUri() to get a DocumentFile on the tree identified by the Uri that you got from ActivityResultContracts.OpenDocumentTree(). You can call listFiles() on that to get DocumentFile objects representing the direct contents of that tree.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading