-2

I want to retrieve the list of songs in a fragment that I'm using for tabbed UI.

public void getSongList(){
    ContentResolver musicResolver = getActivity().getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }

//        musicCursor.close();
}

I am getting a NullPointerException for songList.add(), songList is an ArrayList already defined.

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
                                                                at com.musi.musi2.Tracks.getSongList(Tracks.java:60)

Can someone please help me know what can be the reason?, or if there is another way to do this.

Also, the code works when used in MainActivity instead of fragment

P.S. I am using a phone to test the app, and I have songs in the phone.

Edit: This is not a duplicate to "What is NullPointerException", I know what that is allright, My code works when the getSongList() method is used in the MainActivity and I want to know the reason.

ZERO
  • 1
  • 3
  • 4
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Mike M. Sep 20 '16 at 08:32
  • you might not have been initialised your `arrayList` – Nikhil Sep 20 '16 at 08:32
  • Initialize your `ArrayList` also close your cursor at the end of your `if(musicCursor!=null && musicCursor.moveToFirst())` statement, after your while loop. – Mark Sep 20 '16 at 08:37

1 Answers1

0

Use Below code:

public void getSongList(){
songList = new ArrayList<>; 

...

}
Asif Patel
  • 1,744
  • 1
  • 20
  • 27