Fix: SharedPreferences not saved after app restart

It is quite common error that SharedPreference setting is being reset or cleared to default, after Android application is restarted. There are two things you have to remember.

Commit changes made by prefs editor (the obvious one)

prefsEditor.commit();

Clear prefs editor before using it (the tricky one)

prefsEditor.clear();

The clear() method clears your preferences made by editor. Clear() is also always called in commit() method (so after the change in editor was made).

Summary

So to solve this problem You need to write code like this (compare it with snippets in previous post):

public static void setPushEnabledFlag(Context context, boolean newValue) {
	SharedPreferences prefs = context.getSharedPreferences(Constants.SP_MY_APPLICATION_SETTINGS, 0);
	Editor prefsEditor = prefs.edit();
	prefsEditor.clear();
	prefsEditor.putBoolean(
			context.getString(R.string.settingsActivity_ReceivePushNotifications_key),
			newValue);
	prefsEditor.commit();
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

14 thoughts on “Fix: SharedPreferences not saved after app restart

  1. Hey i have a problem when i make some change in EditTextPreferences
    it does not apply on my application until i restart this application kindly help me how can i apply change on my application by going back on it.

  2. Finally got the solution! You saved my day dude!
    There’s no one mentioned should try clear()…

    1. It took me some time to figure out that clear() is needed. I’m glad I could help and save your time :)

  3. Thanks! But I have a question? If you need put two value (ex: int x, string y) into SharedPreferences with two different method. Fist you clear() and putInt(x) in method one, next clear() and putString(y) in method two. the value of int x will be lost?

    PS: sorry for my bad English.

  4. i dont get when to use clear and when to not
    when i force close my application or reboot device all the data is removed
    basically i was working on project in which sign in login in etc etc but when user sign in and force close then application user have to again sign in

  5. Thanks man! How is this not like everywhere? I kept losing data after app restart. Since I was updating preferences in Application class, IntentService and in different activities… And I had no idea what It lost data, still don’t. But at least now it works! :)

  6. Hi, I want to store my model object to retrieve values from that, when I am trying to do that, it’s getting saved, any help would be amazingly appreciated. thanks in advance.

  7. Thank you!!! I put a lot of effort in order to solve it and you gave me the clearest answer!! good job

Give Your feedback: