简体   繁体   中英

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);
    }

}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM