1

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.

Phil
  • 943
  • 2
  • 6
  • 18
  • where exactly do you get NPE from above code? – SMA Feb 01 '15 at 09:54
  • you have to also check for number of files in every folder. If less than or equal to 0 dont add files. This will resolve the issue. Just check whether folder has files or not – Vilas Feb 01 '15 at 09:55
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Simon Feb 01 '15 at 10:48

1 Answers1

2

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

Blackbelt
  • 156,034
  • 29
  • 297
  • 305