Edit: this code actually works. I had problem in the code that used it. Leaving it anyway in case anybody will find it useful.
I have a class with two methods to write and read a boolean persisted preference. However, if I write a new value and then try to read it, I still get the old value. Only if I kill the app and relaunch it, I do get the new value. Any idea what the problem is?
Context mContext;
....
public void writeFlag(boolean flag) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putBoolean("mykey", flag);
editor.commit();
}
public boolean readFlag() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getBoolean("mykey", false);
}
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With