Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaPlayer throwing IllegalStateException when calling onStop()

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();
            }
        });
like image 794
tyczj Avatar asked May 04 '12 17:05

tyczj


2 Answers

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.

like image 167
zapl Avatar answered Oct 03 '22 01:10

zapl


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());
    }
}
like image 36
Deepak Avatar answered Oct 03 '22 01:10

Deepak