File.listFiles returns null when it shouldn't

自古美人都是妖i 提交于 2020-01-04 09:09:09

问题


I am trying to get list of files existing in the Phone Pictures folder (internal storage, no SDCard inserted) using this:

 File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
 File[] files = file.listFiles();

but files value is always being null. I also add this to AndroidManifest.xml

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

Any ideas will be much appreciated, thanks in advance.


回答1:


If you are targeting Android SDK >=23 you need to take permission at run-time.

https://developer.android.com/training/permissions/requesting.html




回答2:


It returns null as Environment.getExternalStoragePublicDirectory will/is supposed to handle files from external storage like SD card..as you are stating no sd card is inserted




回答3:


As Abhishek Aryan suggested, I am using Android SDK >=23 so I had to obtain permissions using code:

  boolean grantedAll = ContextCompat.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!grantedAll)
   {
     ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSIONS);
   }


来源:https://stackoverflow.com/questions/42133758/file-listfiles-returns-null-when-it-shouldnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!