Reputation: 1129
I have a really simple activity where I am taking the value of SharedPrefs and incrementing it by 1 every time the program is created. Thus i would expect that this would keep incrementing when i open and close(back out) of the program. However it seems like the values aren't saving. I am using commit after each change.
public class SharedPreferencesActivity extends Activity {
/** Called when the activity is first created. */
public static final String PREFERENCE_FILENAME = "MyGamePreferences";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int int_out = 0;
SharedPreferences gameSettings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
int_out = gameSettings.getInt("Username", 0);
Log.e("Pre",Integer.toString(int_out));
int_out = int_out + 1;
Log.e("During",Integer.toString(int_out));
prefEditor.putInt("UserName", int_out);
prefEditor.commit();
int_out = gameSettings.getInt("Username", 0);
Log.e("Post",Integer.toString(int_out));
}
}
The output of my code above from the Log.e statments is
Pre: 0 During: 1 Post: 999
so it seems like after
calling prefEditor.commit();
int_out = gameSettings.getInt("Username", 0);
the SharedPref gameSettings was not saved.
Upvotes: 0
Views: 2510
Reputation: 43023
You have used one key with upper case letter. Change the line
prefEditor.putInt("UserName", int_out);
to
prefEditor.putInt("Username", int_out);
Upvotes: 2