0

I am making a simple game for android, however as I am kind of beginner sometimes I have some problems with basic things and errors in my code. I dont know what is wrong with that code but it seems to crash when I press back button and does not redirect the score from game to main menu.

public void finish(){
    Intent returnIntent = new Intent();
    returnIntent.putExtra("GAME_SCORE",gameView.getHitCount());
    setResult(RESULT_OK, returnIntent);
    super.finish();
  }

GameView:

public int getHitCount(){
    return hitCount;
    }

and MainMenu:

protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
    // Check which request we're responding to
    if (requestCode == SCORE_REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            if (retIntent.hasExtra("GAME_SCORE")) {
                int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
                tvScore.setText(""+Integer.toString(scoreFromGame));
            }
        }   
    }
}
Beda
  • 61
  • 3
  • 12

1 Answers1

2

from what I've understand, the GameActivity returns the user to mainMenuActivity so first thing first the super keyword in java comes always first you can't just put anything before super() and if the game activity returns you to main menu the onFinish() method must be:

super.finish();
Intent returnIntent = new Intent(GameActivity.this,MainMenu.class);
returnIntent.putExtra("GAME_SCORE",gameView.getHitCount());
setResult(RESULT_OK, returnIntent);

and to get the game score if its integer then use:

Intent intent = getIntent();
int intValue = intent.getIntExtra("GAME_SCORE", 0);

in your MainMenu class hope this will help you.

Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
  • Ahmad is right. In the code in the question, you're saying make a new Intent but not sending it anything. You need to send it the sending activity and receiving activity as Ahmad has stated here. – Andrew Quebe Apr 17 '15 at 19:54
  • It helped with the activity to return to main menu once the back button is pressed and it does not crash now, but when it comes to the game score where certainly should I put the above code? – Beda Apr 17 '15 at 20:12
  • okay first in main menu define gameScore as an instance variable inside the class and before onCreate then use getIntent() inside onCreate() and initialize gameScore using the code above then use the variable where you desire – Ahmad Sanie Apr 18 '15 at 05:39
  • delete setResult() from your onFinish() and add startActivity(intent); then use get intent like i've mintioned before in your onCreate and delete the method onActivityResult() or other SOL: use onActivityResult but you must use startActivityForResult in your onFinish() – Ahmad Sanie Apr 19 '15 at 07:30