Search code examples
androidsharedpreferencesandroid-sharedpreferences

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?


Solution

  • 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));
    }