0

I tried to create a MediaPlayer which starts and stops on the same button, like this:

public void song1(View view){    
    if(mp.isPlaying() == true){
        mp.pause();
    }else{
        mp = MediaPlayer.create(this, R.raw.song1);
        mp.start();
    }
}

But my app crashes if I try to click on the Button, so I souroundet it with try and Catch like this:

public void song1(View view){
        try{   
        if(mp.isPlaying() == true){
            mp.pause();
        }else{
            mp = MediaPlayer.create(this, R.raw.song1);
            mp.start();
        }
    }catch (Exception e){
            e.printStackTrace();
        }
    }

Here is the Logcat:

 W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference
 W/System.err:     at com.example.exampleapp.MainActivity.sound1(MainActivity.java:129)
 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 W/System.err:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
 W/System.err:     at android.view.View.performClick(View.java:5264)
 W/System.err:     at android.view.View$PerformClick.run(View.java:21297)
 W/System.err:     at android.os.Handler.handleCallback(Handler.java:743)
 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
 W/System.err:     at android.os.Looper.loop(Looper.java:150)
 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5621)
 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
 I/HwSecImmHelper: mSecurityInputMethodService is null

What does this error mean? And how can I solve it?

Aaron Waller
  • 175
  • 4
  • 21

1 Answers1

6

It means that your MediaPlayer is null, and you're trying to call isPlaying on it.

Rewrite your condition like this to check if it's null first

if(mp != null && mp.isPlaying()){
    ...
tostao
  • 2,803
  • 4
  • 38
  • 61
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55