Home > OS >  listFiles() nullpointerexception when called
listFiles() nullpointerexception when called

Time:10-31

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

CodePudding user response:

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.

  • Related