I use one MediaPlayer. I give it a different sound when you click on each of the 5 buttons like this:

@Override public void onClick(View v) { switch(v.getId()) { case R.id.flats_btn1: flats = MediaPlayer.create(getActivity(), R.raw.carrier); flats.start(); break; 

But I want the sound to not start playing when I press it again when I play it, but to start it only after this sound ends. I do this, but the application crashes with an error:

 @Override public void onClick(View v) { switch(v.getId()) { case R.id.flats_btn1: if (!flats.isPlaying()) flats = MediaPlayer.create(getActivity(), R.raw.carrier); flats.start(); break; 

How to make the application does not stop? LogCat:

 08-13 22:35:45.517: E/AndroidRuntime(937): FATAL EXCEPTION: main 08-13 22:35:45.517: E/AndroidRuntime(937): java.lang.NullPointerException 08-13 22:35:45.517: E/AndroidRuntime(937): at FragmentFlatsMale.onClick(FragmentFlatsMale.java:122) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.view.View.performClick(View.java:4204) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.view.View$PerformClick.run(View.java:17355) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.os.Handler.handleCallback(Handler.java:725) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.os.Handler.dispatchMessage(Handler.java:92) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.os.Looper.loop(Looper.java:137) 08-13 22:35:45.517: E/AndroidRuntime(937): at android.app.ActivityThread.main(ActivityThread.java:5041) 08-13 22:35:45.517: E/AndroidRuntime(937): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 22:35:45.517: E/AndroidRuntime(937): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 22:35:45.517: E/AndroidRuntime(937): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 08-13 22:35:45.517: E/AndroidRuntime(937): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08-13 22:35:45.517: E/AndroidRuntime(937): at dalvik.system.NativeStart.main(Native Method) 08-13 22:35:47.677: I/Process(937): Sending signal. PID: 937 SIG: 9 08-13 22:35:48.517: E/Trace(956): error opening trace file: No such file or directory (2) 

    1 answer 1

    You have an NPE , you are trying to call a method on a link that is null . Those. You do not have in the code a guarantee that at the time of the poll, the player was already in progress. Plus, you do not have brackets for the body if and this leads to the fact that even if the code does not fall on the condition, it can be saved on the music launch line by the same NPE .

    You need to check if the player already exists and only then does it play.

     if (flats == null || !flats.isPlaying()) { flats = MediaPlayer.create(getActivity(), R.raw.carrier); flats.start(); }