0

I would like to know how to add 2 preference values in android?ie consider a game which has coins to gain life and say an user choose not to use that coins and starts game once again.Now lets say he got few more coins.So my question is how to add old non utilized coins+newly obtained coins?

Govind Narayan
  • 91
  • 1
  • 12

2 Answers2

0
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putInt("lifecoin", 5).commit();

Lets say user left 5 coins here. Now you use a while loop like this :

int leftovercoin = 0;
try
{
    leftovercoin = prefs.getInt("lifecoin", 0);
}
catch(Exception e)
{
    Log.e("Error while getting shared pref", "Error while getting shared pref", e);
}
//add your new level's coins(5 of them) to the leftovercoins from last stage
leftovercoin = leftovercoin + 5; //here leftovercoin would be 10 because the shared preference has given it a value of 5 at first
while(leftovercoin>0)
{
      //spawn your coins here
      leftovercoin--;
}
Orphamiel
  • 874
  • 13
  • 22
  • Let me make it simple does any of these code increments preference value say 2 coins in previous game + 5 coins in new game total i need to show 7 coins and user must be able to decrement from those 7 coins. – Govind Narayan Feb 19 '14 at 06:43
  • Updated. instead of using a while loop, you decrement everytime the user does something and spawns a coin. – Orphamiel Feb 19 '14 at 06:44
0

You can use SharedPreferences as

To write To Shared Preferences use:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

And To read from Shared Preferences use:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Himanshu Joshi
  • 3,391
  • 1
  • 19
  • 32