0

I am building a music player. The error occurs when launching the application.

I have searched the term "Caused by: java.lang.NullPointerException" on Google, finding out the cause for this and it seems like it's throwing back null commands of some sort? Whilst looking at the logcat I saw this...

04-06 13:25:16.444: E/AndroidRuntime(30139): Caused by: java.lang.NullPointerException
04-06 13:25:16.444: E/AndroidRuntime(30139):    at com.ascendapps.nexplay.SongsManager.getPlayList(SongsManager.java:25)
04-06 13:25:16.444: E/AndroidRuntime(30139):    at com.ascendapps.nexplay.MainActivity.onCreate(MainActivity.java:79)
04-06 13:25:16.444: E/AndroidRuntime(30139):

So I checked my SongsManager class and was looking at line 25.

public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);
    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

When looking at the code, the error lies in this line if (home.listFiles(new FileExtensionFilter()).length > 0) {

So after doing a bit more research on this, I found a way to bypass this null exception error by changing the code to...

public ArrayList<HashMap<String, String>> getPlayList(){

    Log.d("testsd",MEDIA_PATH);
    File home = new File(MEDIA_PATH);

//  if (home.listFiles(new FileExtensionFilter()).length > 0) //don't use this to avoid null pointer exception !
    if (home.listFiles(new FileExtensionFilter())!=null) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();


            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList


            songsList.add(song);

        }
    }
    // return songs list array
    return songsList;
}

By replacing the code with the one above, it fixed the null exception error but it started giving me another error. This is the error

04-06 13:36:33.754: E/AndroidRuntime(30586): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-06 13:36:33.754: E/AndroidRuntime(30586):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
04-06 13:36:33.754: E/AndroidRuntime(30586):    at java.util.ArrayList.get(ArrayList.java:308)
04-06 13:36:33.754: E/AndroidRuntime(30586):    at com.ascendapps.nexplay.MainActivity.playSong(MainActivity.java:281)
04-06 13:36:33.754: E/AndroidRuntime(30586):    at com.ascendapps.nexplay.MainActivity.onCreate(MainActivity.java:82)

So I checked my MainActivity class and these are the lines the error was on mp.setDataSource(songsList.get(songIndex).get("songPath"));

Line 281 (whole function)

/**
     * Function to play a song
     * @param songIndex - index of song
     * */
    public void  playSong(int songIndex){
        // Play song
        try {
            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);

            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);

            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);

            // Updating progress bar
            updateProgressBar();            
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

And this is line 82

// By default play first song
        playSong(0);

I've been looking at these code for a while. I've been looking at the new errors, but I don't really know what to change? I've tried changing the 0 to a larger number such as the following 1,5,10,15,20 and nothing happened. Same errors. I looked at line 281.

If I am reading these logcats wrong, please let me know. Also If you think I should revert my code back to the point where I get the null point exception error, and if you know how to fix tit from there also let me know. And some tips on how to prevent this error occurring next time. Thanks for reading!

Zong
  • 6,160
  • 5
  • 32
  • 46

3 Answers3

3

If your NullPointerException is being caused by this

home.listFiles(new FileExtensionFilter()).length

then

home.listFiles(new FileExtensionFilter())

seems to be null. This is likely because the listFiles function can return null:

An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Which implies that MEDIA_PATH is not the directory path that you think it is.

The out-of-bounds exception is caused by this line:

mp.setDataSource(songsList.get(songIndex).get("songPath"));

Meaning songIndex does not exist in songsList. As stated in your exception:

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

You can't reference element 0, which is the first element, in a zero-element list.

Since songsList is being added to only as a result of the data found in the MEDIA_PATH directory, and MEDIA_PATH is somehow erroneous... Hopefully when you solve the problem with MEDIA_PATH, both problems will be solved.

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • My MEDIA_PATh directory is set as this - final String MEDIA_PATH = new String("/sdcard/"); - I then changed it to - final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath()); – Little Plastic Soldier Apr 06 '14 at 02:23
  • Hopefully these questions can help you confirm that the directories are recognizable: http://stackoverflow.com/questions/7996524/is-there-a-proper-way-to-check-for-file-directory-existence-in-java and http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-java-on-windows – aliteralmind Apr 06 '14 at 02:37
  • I just want to add, using /sdcard/ or even `getExternalStorageDirectory` may not be correct depending on the device. Also note that `listFiles` is not recursive so your mp3 files must be all in the root. Lastly, you should not do playSong(0) by default, you should check first if there are any songs to play. – singularhum Apr 06 '14 at 02:49
  • I remove btnForward and btnBAckwards as I never added these functions :D The application runs. Now! :D – Little Plastic Soldier Apr 06 '14 at 03:12
2

Please replace your code like this:

if (home.listFiles(new FileExtensionFilter())!=null && home.listFiles(new FileExtensionFilter()).length > 0)
{

}

and check listFiles is containg no list. i.e. either your filepath is not not proper and file doesn't contain any song. Please make sure your sdcard conatins any .mp3 file.

Ankit
  • 483
  • 3
  • 8
-2

I'm pretty sure that in Manifest you forgot the permission to READ EXTERNAL STORAGE, and that's why you got the IndexOutOfBoundsException.

Mitch Talmadge
  • 4,638
  • 3
  • 26
  • 44
Noname
  • 11
  • 1
  • This question already had an accepted answer. If you could explain why the code compiled and ran if that permission was missing, that would be great. – OneCricketeer Jul 17 '16 at 04:41
  • I think because we are working with External storage (sdcard), you want to get all the mp3 type files in sdcard and store it in an ArrayList. If you miss the permission to READ EXTERNAL STORAGE, this code line songsList = songManager.getPlayList(); //you get nothing size=0 Which means there will be an error at mp.setDataSource(songsList.get(songIndex).get("songPath")); //Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 As he said he changed the index to different number such as 0,1,3,15 but the code still didn't work because the size IS 0 – Noname Jul 17 '16 at 05:50