Search code examples
javaandroidandroid-mediaplayer

IllegalStateException in MediaPlayer


Here is my code

if (player != null) {
    if(player.isPlaying()){
        player.pause();
        player.stop();
    }
    player.release();
}

and here is error

FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.mindefy.sindhipathshala.RecViewAdapter.mediafileRelease(RecViewAdapter.java:234)
at com.mindefy.sindhipathshala.SectionFruits.onBackPressed(SectionFruits.java:252)

I am a beginner in Android and i am very confused with the lifecycle of a MediaPlayer.

This is a function in an adapter that is called from onBackPressed() function of another Activity. player is a class variable.

I am releasing this MediaPlayer in same file as

public void onClick(View v) {
    try {
        if (player != null) {
            player.stop();
            player.release();
        }
    } catch (Exception e) {
    }
    player = MediaPlayer.create(activityContext, soundId);
    player.start();
}

Solution

  • The problem is you don't keep track of the state of your MediaPlayer instance.

    Before calling isPlaying() you only perform a null value check, although player can still be released (but not null).

    Calling isPlaying() on a released MediaPlayer instance will result in an IllegalStateException.

    To avoid this, you could for example set player to null when you release it:

    player.release();
    player = null;
    

    Or you could use a boolean flag to keep track of its state:

    boolean isReleased;
    
    // ...
    
    player.release();
    isReleased = true;
    

    So you could check for this flag when necessary:

    if (player != null && !isReleased) {
        if(player.isPlaying()) {
            // ...
        }
    }
    

    (don't forget to set it to false when appropriate)