Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Preferences not persistent after app restart

I found all answers here and tried all solutions, still my shared prefs are not persistent.

Here's my code:

public static void setActivated(boolean activated) {
    SharedPreferences sp = Utils.getContext().getSharedPreferences(
            USER_PREFS, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit(); 
    editor.putBoolean(ASD, activated);
    editor.commit();
}

public static boolean isActivated() {
    SharedPreferences sp = Utils.getContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
    return sp.getBoolean(ASD, true); 
}

I've tried also:

editor.clear();
editor.put ..
editor.commit();

I've also tried with

editor.apply();

I even tried with both .apply() and .commit() and no luck.

Another idea was to try using a different mode for the files:

...getSharedPreferences(USER_PREFS, Context.MODE_MULTI_PROCESS);

The problem is that the values saved are not persistent. If I close the app and then re-open it the values are all wrong.

Does anyone have any ideas? I would also mention that the problem is only on some devices, for example HTC One S, Samsung Galaxy S3 (I tested on a different S3 and it worked perfectly).

EDIT: I call the save on a button click listener and I call isActivated when I load the fragment (after onViewCreated()).

Thanks!

like image 382
Razvan Avatar asked Jun 18 '14 09:06

Razvan


2 Answers

public abstract SharedPreferences.Editor clear()

Added in API level 1 Mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor. Note that when committing back to the preferences, the clear is done first, regardless of whether you called clear before or after put methods on this editor.

Returns Returns a reference to the same Editor object, so you can chain put calls together.

In my user preferences class I was getting a null value on some other strings and my code was something like this:

SharedPreferences sp = Utils.getContext()
    .getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (session != null && !"".equals(session)) {
    sessionId = session;
    editor.putString(SESSION, sessionId).commit();
} else {
    sessionId = null;
    editor.clear().commit();
}

The editor.clear() was resetting all my other commits!

like image 160
Razvan Avatar answered Oct 26 '22 18:10

Razvan


Hi I think it should work. If clearing does not work, you could try the second option as detailed in my solution:

You have 2 options:

  1. Get shared preference value during the life-cycle of the activity.

  2. Call .clear before .commit

See my answer:

Android Persistent Checkable Menu in Custom Widget After Reboot Android

like image 31
iOSAndroidWindowsMobileAppsDev Avatar answered Oct 26 '22 18:10

iOSAndroidWindowsMobileAppsDev