IllegalStateException in MediaPlayer

Here is my code

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

and here is the mistake

 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 new to Android and I am very confused by the MediaPlayer life cycle.

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

I am releasing this MediaPlayer in the 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(); } 
+6
source share
1 answer

The problem is that you are not monitoring the state of your MediaPlayer instance.

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

Calling isPlaying() on the released MediaPlayer instance will IllegalStateException .

To avoid this, you can, for example, set player to null when it is released:

 player.release(); player = null; 

Or you can use the boolean flag to track its status:

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

Thus, you can check this flag if necessary:

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

(don't forget to set it false if necessary)

+4
source