Yamaha T64312
Yamaha T64312

Reputation: 103

Android Shared Preferences don't Save Properly

I am trying to use Android Shared Preferences to save certain app values Here is the code of my onCreate:

protected void onCreate(Bundle savedInstanceState) {

    SharedPreferences preferences = getSharedPreferences("MyPref", MODE_PRIVATE);
    boolean firstLaunch = preferences.getBoolean("firstlaunch", true);

    System.out.println("FIRST LAUNCH? " + firstLaunch);

    if(firstLaunch == true){
        SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
        editor.putString("language", "en");
        editor.putInt("theme", R.style.Default);
        editor.putBoolean("firstLaunch", false);
        editor.commit();
        System.out.println("FIRST LAUNCH:" + preferences.getBoolean("firstLaunch", true));
    }

When I restart the app, firstLaunch is still true? Why is this?

Upvotes: 1

Views: 445

Answers (2)

Distwo
Distwo

Reputation: 11749

You have a case issue. firstlaunch vs firstLaunch

To avoid this kind of problem you should use a static member.

private static final String KEY_PREFS_NAME = "myPrefs";
private static final String KEY_FIRST_LAUNCH = "firstLaunch";

protected void onCreate(Bundle savedInstanceState) {

SharedPreferences preferences = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE);
boolean firstLaunch = preferences.getBoolean(KEY_FIRST_LAUNCH, true);

System.out.println("FIRST LAUNCH? " + firstLaunch);

if(firstLaunch == true){
    SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putString("language", "en");
    editor.putInt("theme", R.style.Default);
    editor.putBoolean(KEY_FIRST_LAUNCH, false);
    editor.commit();
    System.out.println("FIRST LAUNCH:" + preferences.getBoolean(KEY_FIRST_LAUNCH, true));
}

Upvotes: 3

Pztar
Pztar

Reputation: 4749

Your key value is not spelled properly when you retrieve it so you always get true change and you commit to the wrong key.

Change

 boolean firstLaunch = preferences.getBoolean("firstlaunch", true);

to

 boolean firstLaunch = preferences.getBoolean("firstLaunch", true);

Upvotes: 3

Related Questions