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.