1

I am trying to make my app read and show all the song files in it but whenever i am trying to run my app it keeps getting crashed. In my logcat 'java.lang.NullPointerException: Attempt to get length of null array' error keeps showing. And I know the problem is somewhere in the bellow code:

public ArrayList<File> findSong(File file){
        ArrayList<File> arrayList= new ArrayList<>();
       
        File[] files=file.listFiles();

        for (File singleFile : files){
            if(singleFile.isDirectory() && !singleFile.isHidden()){
                arrayList.addAll(findSong(singleFile));
            }
            else {
                if(singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav"));
                {
                    arrayList.add(singleFile);
                }
            }
        }
        return arrayList;
    } 

Please help me .

  • Check for null before use. – blackapps May 29 '21 at 10:48
  • if(files==null) return; – blackapps May 29 '21 at 10:49
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zain May 29 '21 at 11:00
  • docs on `listFiles`: `If this abstract pathname does not denote a directory, then this method returns null. ` https://developer.android.com/reference/java/io/File#listFiles() –  May 29 '21 at 11:06

1 Answers1

0

Try this one:

public ArrayList<File> findsong(File file) {
    ArrayList<File> arrayList = new ArrayList<File>();
    File listfiles[] = file.listFiles();
    if (listfiles != null) {
        for (int i = 0; i < listfiles.length; i++) {
            if (listfiles[i].isDirectory()) {
                arrayList.addAll(findsong(listfiles[i]));
            } else {
                if (listfiles[i].getName().endsWith(".mp3")||singleFile.getName().endsWith(".wav")) {
                    arrayList.add(listfiles[i]);
                }
            }
        }
    }

    return arrayList;
}