Home » Android » android – MediaPlayer throwing IllegalStateException when calling onStop()

android – MediaPlayer throwing IllegalStateException when calling onStop()

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have an AlertDialog, which stops playing a sound when I have clicked, but on some devices it appears that calling onStop() throws an IllegalStateException, but why?

If the dialog is up, that means the sound is playing, so it should be a case where the audio is not playing.

I surrounded it with a try catch for now, but what would cause this?

alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                try{
                mp.stop(); //error
                mp.reset();
                mp.release();
                }catch(Exception e){
                    Log.d("Nitif Activity", e.toString());
                }
                v.cancel();

                popupMessage();                 
                finish();
            }
        });
How to&Answers:

I guess you might be nulling your instance before executing these lines.
When I got this error I check for null first.

if (mp != null) {
    try {
        mp.stop(); //error
        mp.reset();
        mp.release();
    } catch(Exception e){
        Log.d("Nitif Activity", e.toString());
    }
}

Answer:

Checking mp != null prevents a NullPointerException but the IllegalStateException can’t be caused by that.

The reason you get that error is that the player is in a state where it can’t stop(). If you have a look at the state-diagram at the top of the MediaPlayer documentation you can see that stop can only be called after the player is in the Prepared state. The next possibility is that you have already called release() or reset() which will also result in that error.

You can call stop() only in Prepared, Started, Paused, PlaybackComplete or Stopped state. All other states produce that error.

So you either do prepareAsync() and the user hits the button before your player is prepared or you have code that releases or resets the player before you hit the button.

Answer:

Apparently mp isn’t initialized, Dev Resource;

Try adding:

if(mp != null)

Answer:

Checking mp!=null prevents when it is null, but your mediaplayer never goes null.
just add mp=null; where you are doing mp.stop();