Search code examples
javaandroidandroid-mediaplayer

Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference


I am trying to stop a music using the back button of the phone. It will function when there is music playing but returns this error Attempt to invoke virtual method boolean android.media.MediaPlayer.isPlaying() on a null object reference when there is no music playing.
Here is my code

 public void play_nature(View g){

    natureMP = new MediaPlayer();
    try {
        natureMP.setDataSource("https://firebasestorage.googleapis.com/v0/b/capstone-katugna-001.appspot.com/o/Relax%201%20Minute%20-%20Rainforest%20Sounds%20Waterfall%20and%20Rain.mp3?alt=media&token=d01bd960-9de5-4835-a9ef-a4d997fad3f6");
        natureMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

        natureMP.prepare();

    } catch (IOException e) {
        e.printStackTrace();
    }

    pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            natureMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.pause();
                }
            });
            natureMP.pause();
        }
    });

}
@Override
public void onDestroy() {
    super.onDestroy();
    if(natureMP.isPlaying() == true){
        natureMP.stop();
    }
    else if(!natureMP.isPlaying()){
        Intent i = new Intent(getApplicationContext(), MusicActivity.class);
        startActivity(i);
    }

}

Solution

  • natureMP is being initialized in play_nature(), unless there's some guarantee that method will always be called before onDestroy() being called, you should probably add a check for null in the onDestroy() method.

    if(natureMP != null) {
        if(natureMP.isPlaying()){
            natureMP.stop();
        }
        else{
            Intent i = new Intent(getApplicationContext(), MusicActivity.class);
            startActivity(i);
        }
    }