Fix: SharedPreferences not saved after app restart

21 09 2012

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!

Advertisements







%d bloggers like this: