Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read/write a boolean preference

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);
}
like image 669
user1139880 Avatar asked Apr 29 '12 04:04

user1139880


1 Answers

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()
like image 102
Shankar Agarwal Avatar answered Oct 11 '22 13:10

Shankar Agarwal