-1

I have four buttons of my main menu for my android game. In my option, there's on and off. When the user clicks the on button, the music should play when I start to click play. And if the user clicks the off, the music will not play. But the default is, the music will play.

I tried to code on my own, if the user clicks the on button, there's this sign variable will set to 1 and this value will pass to the play activity. Where if the sign value is equivalent to 1, the music will start; if 0, the music will not play. But, after doing this, after I click off, it results to "FORCE CLOSE" of my game.

I have this code for my Options activity:

musicOn.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    Intent put = new Intent(getApplicationContext(), Level1.class); 

    musicSwitch = 1;
    Bundle cargo = new Bundle();
    cargo.putInt("sign", musicSwitch);

    put.putExtras(cargo);
    }
});

musicOff.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    Intent put = new Intent(getApplicationContext(), Level1.class);             
    musicSwitch = 0;
    Bundle cargo = new Bundle();
    cargo.putInt("sign", musicSwitch);

    put.putExtras(cargo);
    }

});

And this one for my level1 activity:

int value=1;

Bundle cargo = getIntent().getExtras();
value = cargo.getInt("sign");

if(value==1){
MediaPlayer mPlayer = MediaPlayer.create(Level1.this, R.raw.sounds);
mPlayer.start();
mPlayer.setLooping(true);
}
Community
  • 1
  • 1
pingboo23
  • 137
  • 1
  • 3
  • 15

2 Answers2

0

please post the logcat to be more accurate.

I think it's force closing because you didn't tell it what to do when the value is equal to 0.

if(value==1){
MediaPlayer mPlayer = MediaPlayer.create(Level1.this, R.raw.sounds);
mPlayer.start();
mPlayer.setLooping(true);
} else if(value == 0){
mPlayer.stop();
}

and I recommend you to make the mPlayer static not in the if statement only.

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
0

You are creating Intents but not doing anything with them. I think you are assuming that

Intent put = new Intent(getApplicationContext(), Level1.class); 

will allow you to add an extra to the Intent that initially launched your Activity, but that is not the case. This Intent you created won't do anything unless you use it to launch a new activity. It will just get dumped by the GC after the onClick method is done.

So when you run getIntent().getExtras(); the Bundle it returns will not include the extras you added in that onClick method.

It would be better to use a static member variable that can be accessed by both the view and the activity. And if you want it to persist between sessions of the game, store it in a SharedPreference.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154