Debug NullPointerException

筅森魡賤 提交于 2019-12-25 09:20:37

问题


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!


回答1:


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.




回答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.




回答3:


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



来源:https://stackoverflow.com/questions/22889056/debug-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!