listFiles()返回null,但是在该目录中有可用文件时,我还请求了Runtime中的READ_EXTERNAL_STORAGE权限,仍然面临相同的问题。我的SDK版本29
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
File file = new File(Environment.getExternalStorageDirectory().toString() + WHATSAPP_DIR_LOCATION);
Log.d("LOL",String.valueOf(file));
MyAdapter recyclerAdapter = new MyAdapter(this.getListFiles(file),MainActivity.this);
recyclerView.setAdapter(recyclerAdapter);
}
else {
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
},REQUEST_CODE);
}
private ArrayList<File> getListFiles(File parentDir){
ArrayList<File> inFiles = new ArrayList<>();
File[] files;
files = parentDir.listFiles();
Log.d("Test1","hey");
if (files != null){
Log.d("Test2","hey");
for (File file: files){
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".gif") || file.getName().endsWith(".mp4")){
if (!inFiles.contains(file))
inFiles.add(file);
}
}
}
return inFiles;
}