1

I am having trouble storing primitive data in an instance of SharedPreferences. Everything works as I thought it would, but when I close or exit my app and reopen it, the values in the SharedPreference go back to the default states.

I think it may have to do with either where or how I set the default values. Here is the snippet I am referring to that resides in the onCreate() of my main activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null){
        userDetails = getSharedPreferences("preferences", MODE_PRIVATE);
        SharedPreferences.Editor edit = userDetails.edit();
        edit.putInt("list_code", 0);    //stores the number corresponding to a word list
        edit.putInt("highscore", 0);    //stores the starting score
        edit.commit();
    }

Thougts?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
n.c
  • 13
  • 2

1 Answers1

1

The Bundle != null when your activity "restarts". For instance when screen was rotated or system killed background activity and recreated it. Otherwise it equals null. So to save some data between different instances of activity you need to check whether you save data before or not.

Sample:

SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
int highScore = preferences.getInt("highscore", -1);

if (highScore == -1) {
    //preferences was never used, so put default value
    highScore = 0;
    preferences.edit().putInt("highscore", highScore).commit();
}
eleven
  • 6,779
  • 2
  • 32
  • 52
  • faster by a couple of seconds. also this answer adds some light http://stackoverflow.com/a/5901770/1368705 – appoll May 19 '15 at 16:03