Search code examples
androidmedia-playeronbackpressed

Stop sound file when back pressed in Android


I have some audio files in listview which I play them randomly. while the file is playing I want to go back by pressing the back button, so in method onBackpressed I put the following

 if(mMediaPlayer.isPlaying())
    {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }else
    {
        //show a message or something
    }

but its not working and I get a FATAL EXCEPTION MAIN NullpointerException in the case the audio its not playing


Solution

  • Try this code , it may help you

     if(mMediaPlayer!=null && mMediaPlayer.isPlaying())
        {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }else
        {
            //show a message or something
        }