File exists and IS directory, but listFiles() returns null

Viewed 68051

The documentation for File.listFiles() suggests that null will ONLY be returned in the case that the file calling it is not a directory.

I have the following:

String dir = "/storage/emulated/0";
File f = new File(dir);
Log.v("Files",f.exists()+"");
Log.v("Files",f.isDirectory()+"");
Log.v("Files",f.listFiles()+"");

The log reads:

true
true
null

For some reason, listFiles() is returning null even though the File is recognized as a valid directory. I'm not super familiar with Android file hierarchy behavior, so I would guess the problem lies in there.

For reference, I'm debugging on my Moto X, and results are the same whether the phone is plugged in to my computer or not - so I don't think it has to do with mounting when plugged in.

12 Answers

In addition to other answers and comments, I'd suggest you check whether you need

<application android:requestLegacyExternalStorage="true"

in your manifest. It seems that some recent apis need it.

Anyway, zapl's comment is rather short but quite insightful. You can "ls -ld" the directory on the device (via "adb shell" or some other shells). If you have "r" permission on the directory, you can call listFiles(). Otherwise, it returns null. Note that you can access files under the unreadable directory if you know the file names and have "x" permission on the directory. You can know who you are by "whoami" and "groups" commands.

  1. List item

Add this in your AndroidManifest.xml <application android:requestLegacyExternalStorage="true" .../> It worked for me.

@tamo's answer resolved my issue, i compile exoplayer on ANQ, and set :

build.gradle :

android {
compileSdkVersion 29
buildToolsVersion '29.0.0'

defaultConfig {
    minSdkVersion 16
    targetSdkVersion 29
}

manifest.xml :

  <application
  android:name="com.google.android.exoplayer.demo.ExoPlayerDemoApplication"
  android:label="@string/application_name"
  android:icon="@drawable/ic_launcher"
  android:largeHeap="true"
  android:allowBackup="false"
  android:requestLegacyExternalStorage="true">

i check android develop site, it's already explain this : https://developer.android.com/training/data-storage/compatibility

if you target API 29 or higher, just follow google's setting.

First make sure that you are asking the permission for reading the external storage

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

if you want you can the Dexter library for asking permission it is very easy to ask permission using the dexter library

here is the link to that

Dexter library

then after that add the following tag in the <application tag in the manifest

android:requestLegacyExternalStorage="true"

then the listFiles() function will not return null array

Related