Reputation: 217
As i know the basic of save int value with sharedpreferences method is using this
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("savedscore", Score);
editor.commit();
and then we can get the int value in another activity using this
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
Score = pref.getInt("savedscore", 0);
Scoretext = (TextView)findViewById(R.id.textscore);
Scoretext.setText(String.valueOf(score));
and my question is how to totalize all the score that we got when we playing in another activity?
example ;
when i play for the first time i got the score 4000 , so of course when we use this method editor.putInt("savedscore", Score);
it will save the score value and then we got the score value in another activity with using this Score = pref.getInt("savedscore", 0);
it will make the int Score value to 4000
and then i play again then i got score 2000 , so of course the sharedpreferences Score = pref.getInt("savedscore", 0);
int Score value will change to 2000 and not totalize
so that is my question how to Totalize the score?
Upvotes: 1
Views: 78
Reputation: 13558
Simply create another preference entry "totalScore" and increment it accordingly (each time you save a new score):
//...
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("savedscore", Score);
editor.commit();
updateTotalScore(Score)
//..
private void updateTotalScore(int newScore){
SharedPreferences pref = getSharedPreferences("totalScore", MODE_PRIVATE);
int current = pref.getInt("totalScore", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("totalScore", current+newScore);
editor.commit();
}
private int getTotalScore(){
SharedPreferences pref = getSharedPreferences("totalScore", MODE_PRIVATE);
return pref.getInt("totalScore", 0);
}
Upvotes: 1