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

Rona

New Member
#1
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
Mã:
 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);
    }

}
 

Admin

Administrator
Thành viên BQT
#2
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.
Mã:
if(natureMP != null) {
    if(natureMP.isPlaying()){
        natureMP.stop();
    }
    else{
        Intent i = new Intent(getApplicationContext(), MusicActivity.class);
        startActivity(i);
    }
}
 
OP
OP
R

Rona

New Member
#3
WOW. its working. i tried to do if(natureMP != null && natureMP.isPlaying)

it seems that the condition was not right. Your code is working thank you. :)
 
Top