I'm trying to get all files of a specific directory on the SD card. Therefore I found this function
public static List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".mp3")){
inFiles.add(file);
}
}
}
return inFiles;
}
The problem is the following: If the folder is empty, it will throw a NullPointerException. How can I avoid this?
Permissions for read and write on external storage are set.
there is not much to do, if you have to check against null
File[] files = parentDir.listFiles();
if (files == null) {
return inFiles;
}
in your case inFiles
is an empty collection, try to iterating on an empty collection will not case any issues
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.