Reputation: 49
I am trying to update a counter in my Shared Preferences on android. I have a property "coin count" which I would like to manipulate, so far I have managed to use "Shared Preferences" to save the coin value after the application is closed but i cannot manipulate these values. I want the application to take the old coin count and add it to the new coin count. However the value is just overwritten
My method to save the coins:
private void saveCoins(){
SharedPreferences.Editor editor2 = coins.edit();
int newScore = score/10;
editor2.putInt("coinNum", score);
editor2.apply();
}
I retrieve the coin count as following:
TextView coinDisp = findViewById(R.id.coinDisp);
final SharedPreferences coins = getSharedPreferences("game", MODE_PRIVATE);
coinDisp.setText("Coins: " + coins.getInt("coinNum", 0));
Upvotes: 0
Views: 133
Reputation: 133
Try to do so:
public void saveCoins(String key, int value)
{
SharedPreferences.Editor editor3 = coins.edit();
editor3.putInt("coinNum", value + coins.getInt("coinNum", 0));
editor3.commit();
}
Upvotes: 1