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?
Asked
Active
Viewed 99 times
0
-
You can Add it in Sqlite database.. – Prashant Mishra Feb 19 '14 at 06:35
-
@PrashantMishra is there any alternative other than database.ie using shared preference to store and add two preferences vlaues? – Govind Narayan Feb 19 '14 at 06:36
-
in your app create preference activity and show your total coins in that and update it...http://stackoverflow.com/a/9278088/1765530 – appukrb Feb 19 '14 at 06:39
-
@PrashantMishra ? – Govind Narayan Feb 19 '14 at 06:39
-
as your Question Says you have to update the value.. preferable will be to use sq lite.. you can also use SP by updating the value of Score Field.. and use other field to check whether he uses coins or not. – Prashant Mishra Feb 19 '14 at 06:41
2 Answers
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