I am developing a game on Android, I have a background music that I would like to stop using a switch that is in an activity other than the one where I launch the music, that of the parameters. The music is in the main menu.
Here is my class for the music:
public class BackgroundMusic {
private MediaPlayer player;
public Menu context;
public BackgroundMusic(Menu pContext) {
context = pContext;
player = MediaPlayer.create(context.getApplicationContext(), R.raw.opening);
player.setLooping(true);
player.setVolume(1.0f, 1.0f);
}
public void start() {
player.start();
}
public void stop(){
player.pause();
}
}
And here is the code I use for the switch:
buttonmusique = (Switch) findViewById(R.id.switch3);
buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("bouton",String.valueOf(buttonmusique.isChecked()));
// If the music is playing
if (isChecked) {
media.start();
buttonmusique.setText("Musique On"); //To change the text near to switch
Log.d("You are :", "Checked");
} else {
media.stop();
// Resume the music player
buttonmusique.setText("Musique OFF"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
The problem is that, if I press the switch, it sends me back to the main menu (on some phones the application crashed).
This is the logcat :
E/bouton: false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pts3.botanicagofinal, PID: 14271
java.lang.NullPointerException: Attempt to invoke virtual method 'void pts3.botanicagofinal.BackgroundMusic.stop()' on a null object reference
at pts3.botanicagofinal.Parametres$3.onCheckedChanged(Parametres.java:61)
at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
at android.widget.Switch.setChecked(Switch.java:1071)
at android.widget.Switch.toggle(Switch.java:1066)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:22314)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
I want to know if it is possible to do otherwise for it to work or if I have an error in my code?
Thank you in advance for your feedback.