问题
I am trying to make a list of all the files in my external storage but always comes back null.
if (Environment.getExternalStorageDirectory().exists()) {
Log.i(FILE, "is not empty");
File[] files = Environment.getExternalStorageDirectory().listFiles();
for (File file : files) {
Log.i("File ", file.getAbsolutePath());
}
}
How do I make it list all the files from the external directory
I get an exception
Caused by: java.lang.NullPointerException
at com.example.sam.read.fragments.MyFragment.onCreate(MyFragment.java:138)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1763)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:913)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
at android.app.Activity.performStart(Activity.java:5114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
回答1:
You are missing a permission in your manifest. Add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
to your manifest.
回答2:
The NullPointer
is probably coming from for (File file : files)
, reason being that files
is null.
From the documentation, listFiles()
will return null if the specified path is not a directory; what it does not tell you is that you will most likely also get this value if you have a FileSystem permissions issue.
if ( Environment.getExternalStorageDirectory().exists() )
Do you have the required permissions defined in your manifest?
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If this is not the issue, then my only thought is that FILE
is null, or line 138 is not in this snippet.
来源:https://stackoverflow.com/questions/34661450/trying-to-list-all-folders-files-from-internal-sdcard-android-but-get-a-null