Mike
Mike

Reputation: 825

SharedPreferences variable not working properly

I'm trying to store a value to keep score every time that I recreate an activity in a class called GameActivity. I put the following piece of code in my onCreate() method:

SharedPreferences settings = getSharedPreferences("Score", 0);
    int lastscore = settings.getInt("Score", 0 );
    score=lastscore;
    mScoreView.setText("Score: "+ score);

mScoreView is a TextView object that is suppose to update with the current score each time the activity is recreated, score is an instance variable. I have a button which pops up at the end of each game which lets a user keep playing by recreating the activity. Here is the click listener for that button:

private class MyButtonListener2 implements OnClickListener {

    public void onClick(View v) {
        State player = mGameView.getCurrentPlayer();
        Bundle myBundle=new Bundle();
          firstGame=false;

        if (player == State.WIN) {
            if(player==State.WIN){
                SharedPreferences scoreSaved = getSharedPreferences("Score",0);
                SharedPreferences.Editor edit = scoreSaved.edit();
                edit.putInt("Score", score++);
                edit.commit();
                //onCreate(myBundle);
        }
            else{
                myBundle.putInt("score1", 0);
                //onCreate(myBundle);
            }
                 GameActivity.this.recreate();
                 onCreate(myBundle);
}}

The score is suppose to increment by one each time that the game ends with the human player winning (State.WIN). However, the score doesn't update properly. I'm having trouble catching the error

Upvotes: 0

Views: 91

Answers (1)

SteveR
SteveR

Reputation: 2506

use:

edit.putInt("Score", ++score);

or

edit.putInt("Score", score + 1);

Upvotes: 1

Related Questions