Search code examples
androidonclickmedia-playerandroid-mediaplayeronpause

How to stop MediaPlayer onPause() if i declare/start it inside the onButtonClick method?


I am a noob programer and I encountered a problem, I have a mediaplayer.start() inside an onClick method, if i call

mediaplayer.stop(); 
mediaplayer.reset();
mediaplayer.release();

it will crash and get the error:

Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference ".

I tried How to stop the mediaplayer playing from other methods but when I used it I've got a:

"Unable to destroy activity {...Activity}: java.lang.IllegalStateException"

Any support is highly appreciated


Solution

  • Just check if the MediaPlayer is null:

    if(mediaplayer != null) {
        mediaplayer.stop(); 
        mediaplayer.reset();
        mediaplayer.release();
    }