MediaPlayer throwing IllegalStateException when calling onStop()
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.
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());
}
}