Reputation: 1042
I have 4 puzzle games, sub-games lets say, in my game. For each user earns some points. After game1 ends I set earned points to a public static int pointsGame1 variable. And so on for other games. I my main menu I have a box that should display total points. I do something like this:
boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4);
Problem is when I start that activity I get 0000, cause start value for all variables is 0.
And the second problem I have is when I finish my game1 I add those points to my totalPoints variable, also public static int, like this:
Menu.totalPoints =+ pointsGame1;
But when I play second game it should total all my points and display it in mu total box, but instead I only get points from last played game. Also if I earned 60 points in my first game it will display 00060.
How to resolve those two things?
Upvotes: 0
Views: 126
Reputation: 4595
Use SharedPreferences
in your Activity.
To be precise: using shared preferences from different activity/services/intents/... you should use it with mode MODE_MULTI_PROCESS (constant value int = 4). If not, file gets locked and only one process can write it at once!
SharedPreferences preferences = getSharedPreferences("myapp",4);
SharedPreferences.Editor editor = preferences.edit();
int points= pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4;
editor.putInteger("points", points);
editor.commit();
SharedPreferences preferences = getSharedPreferences("myapp",4);
points= preferences.getInteger("points", 0);
points= point+pointsGame1;
SharedPreferences.Editor editor = preferences.edit();
editor.putInteger("points", points);
editor.commit();
And any time you need to persist the points across Activities use the code above.
Then when you need to retrieve the points from any of your Activities/Processes:
SharedPreferences preferences = getSharedPreferences("myapp", 4);
points= preferences.getInteger("points", 0);
Upvotes: 2