Reputation: 61
Util class holding Media player create method:
{
private static ArrayList<Song> allSongs;
private static ArrayList<Song> favouriteSongs;
private static int id = 0;
Context context;
public Util(Context context) {
this.context = context;
}
public Util() {
if (allSongs == null){
allSongs = new ArrayList<>();
initializingAllSongs();
}
if (favouriteSongs == null){
favouriteSongs = new ArrayList<>();
}
}
public static ArrayList<Song> getAllSongs() {
return allSongs;
}
public static ArrayList<Song> getFavouriteSongs() {
return favouriteSongs;
}
public void addToFavSongs(Song song){
favouriteSongs.add(song);
}
public void removeFromFavSongs(Song song){
favouriteSongs.remove(song);
}
private void initializingAllSongs(){
int songNumber = 0;
String songTitle = "";
String songLyrics = " ";
MediaPlayer audioPlayer ;
id++;
songNumber = 1;
songTitle = "Sample song Title ";
songLyrics = "Sample lyrics Sample lyrics \n" +
" Sample lyrics Sample lyrics \n" +
"Sample lyrics Sample lyrics \n" +
" Sample lyrics Sample lyrics";
audioPlayer = new MediaPlayer();
audioPlayer = MediaPlayer.create(context.getApplicationContext(), R.raw.audio);
allSongs.add(new Song(id, songNumber, songTitle, songLyrics, audioPlayer ));
id++;
songNumber = 2;
songTitle = "Sample song Title ";
songLyrics = "Sample lyrics Sample lyrics \n" +
" Sample lyrics Sample lyrics \n" +
"Sample lyrics Sample lyrics \n" +
" Sample lyrics Sample lyrics";
audioPlayer = new MediaPlayer();
audioPlayer = MediaPlayer.create(context.getApplicationContext(), R.raw.audi);
allSongs.add(new Song(id, songNumber, songTitle, songLyrics, audioPlayer ));
}
}
MainActivity (part of it):
recyclerView = findViewById(R.id.songsRecView);
SongRecViewAdapter adapter = new SongRecViewAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Util util = new Util();
ArrayList<Song> allSongs = new ArrayList<>();
allSongs = util.getAllSongs();
adapter.setSongs(allSongs);
Logcat: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at com.example.mrfpc.Util.initializingAllSongs(Util.java:62) at com.example.mrfpc.Util.(Util.java:22) at com.example.mrfpc.MainActivity.onCreate(MainActivity.java:36)
Upvotes: 0
Views: 120
Reputation: 388
This is happening because you haven't initialized Context
in the constructor your initializing in your activity.
Add Context
in second constructor and remove the one that has it, initialize it there and it won't throw it anymore.
Upvotes: 1