Mike
Mike

Reputation: 825

Keep Variable Value while recreating Activity

Can anybody tell me of a way that I can consistently update a variable used to keep tracking of score in a game when I recreate the activity?

Every time the game ends, the user has the opportunity to "keep playing" which resets the game, this also resets the score since the variable is in the GameActivity class. Would I have to create a separate class and pass the score there as a bundle and then pass it back on recreation?

Thanks.

Upvotes: 0

Views: 1129

Answers (2)

idanakav
idanakav

Reputation: 1486

You could use SharedPreferences

To put/edit data :

SharedPreferences score = getSharedPreferences("Score",0);
                    SharedPreferences.Editor edit = score.edit();
                    edit.putInt("Scores", 50);
                    edit.commit();

to get data :

   SharedPreferences score = getSharedPreferences("Score", 0);
   int score = settings.getInt("Score", 0);

Upvotes: 2

Dessus
Dessus

Reputation: 2177

You could take a look at the examples here: http://developer.android.com/guide/topics/data/data-storage.html

I think you might be after the internal storage option.

To set and reset variables, I think you can use the onPause/onResume/onCreate activity overrides to decide when to update your variables. You would also probably have a method to reset the score. I think making your own class for this ability in your application makes sense as it will help separate out score board logic from the rest of your code.

Upvotes: 0

Related Questions