Search code examples
androidandroid-sharedpreferences

Why does the getBoolean always return default?


I'm using SharedPreferences to store the value of multiple checkboxes and some strings, and it's doing well. When I try to use it to store the value of a switch it doesn't work, and keep getting the default value.

I initialize like this

SharedPreferences.Editor editor;
SharedPreferences prefs;

I put this on "onCreate"

editor = getSharedPreferences(FirstStart.MY_PREFS_NAME, MODE_PRIVATE).edit();
prefs = getSharedPreferences(FirstStart.MY_PREFS_NAME, MODE_PRIVATE);

And then I'm testing it on the "onClick" event of the switch (I'm using toasts to test)

public void clickSwitchAlarm(View view) {
    editor.putBoolean("swAlarma", swAlarm.isChecked());
    Toast.makeText(MainMenu.this, "isChecked() value: " + swAlarm.isChecked(), Toast.LENGTH_SHORT).show();
    //Toast.makeText(MainMenu.this, "getBoolean value: " + prefs.getBoolean("swAlarma", false), Toast.LENGTH_SHORT).show();
}

When I check the "isChecked()" value it works fine, but when I check the SharedPreferences stored value it shows the default.

Does anybody know what's happening here? Thank you!

(Working with API15)


Solution

  • After putting the value inside the editor, you must confirm the operation by calling commit() or apply() method`s :

    editor.commit();
    //or
    editor.apply();
    

    Otherwise your operation will not be validated and the value will not be saved.