PKlumpp
PKlumpp

Reputation: 5233

SharedPreferences does not store value

I am currently working with SharedPreferences in Android, and I encountered a weird behavior I cannot explain. This is my code:

SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
appPreferences.edit().putBoolean("launched_before", true);
appPreferences.edit().apply();
appPreferences = null;
appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false); //this is false

The value that I write to my SharedPreferences is not being saved. I know I could use getDefaultSharedPreferences(), but I do not want to do this here, as the default file stores other values.

When I use commit() instead of apply(), the return value of commit() is true, but I still cannot load the file correctly.

Upvotes: 0

Views: 144

Answers (2)

George Y.
George Y.

Reputation: 11799

This happens because your code doesn't do what you think. When you call edit(), it does not start an "edit transaction". Instead it returns a new instance of Editor object each time you call it. So let's look at this code:

SharedPreferences appPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);

// Here you create a FIRST Editor object, which stores the modification
// You never call apply() on this object, and thus your changes are dropped.
appPreferences.edit().putBoolean("launched_before", true);

// Here you create a SECOND Editor object (which has no modifications)
// and you call apply() on it, thus changing nothing.
appPreferences.edit().apply();

You created the first editor object which you put settings in, but you called apply on the second editor object which had no changes. Since you never called apply() on the editor object which had modification, your change was never saved.

The fix is obvious - use a single instance of Editor for your modification, and call apply/commit on this instance:

SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = appPreferences.edit();
ed.putBoolean("launched_before", true);
ed.apply();

Upvotes: 1

Milos Lulic
Milos Lulic

Reputation: 627

Here you can use as key "com.yourdomain.yourapp.your_key_name" and for each value use another key...try this

private SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);

public void putBoolean(String key, boolean value) {
    checkForNullKey(key);
    preferences.edit().putBoolean(key, value).apply();
}

public boolean getBoolean(String key) {
    return preferences.getBoolean(key, false);
}

public void checkForNullKey(String key){
    if (key == null){
        throw new NullPointerException();
    }
}

Upvotes: 0

Related Questions