Question

In an activity I'm using two media players for different sounds, if both sounds are played and the back button is pushed there is no problem, it works fine. the media players stop and release.(mp is set to loop, mps just plays a short sound)

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    mp.stop();
    super.onPause();
}
@Override
protected void onStop() {
    // TODO Auto-generated method stub
    mp.release();
    mps.release();
    super.onStop();
}

But, if one and/or both sounds are not played I get a forced close when the back button is pushed and a null pointer exception. How would you write code to check if the mediaplayers were ever used and therefore need to stop and release them?

Was it helpful?

Solution

If you are getting a null pointer in your onPause and onStop you need to check if mp is null.

@Override
protected void onPause() {
    if (mp != null)
      mp.stop();
    super.onPause();
}
@Override
protected void onStop() {
   if (mp != null)
    mp.release();
   if (mps != null)
    mps.release();

    super.onStop();
}

You can keep a count if you would like to but that means keeping track of another variable when you already have access to the variables you need

OTHER TIPS

could you use a count and add one to it if there has been a play then check if it equals 0 or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top