Richard Norton
Richard Norton

Reputation: 69

SharedPreferences are updated but reset when app is reset

Whenever I start my app I have the following code:

C.userPreferences = getSharedPreferences("default",0);
C.userPreferencesEditor = C.userPreferences.edit();

C.something = C.userPreferences.getStringSet(C.SOMETHING, null);
C.something = C.something == null ? new HashSet<String>() : C.something;

for(String str : C.something){
    Log.d("debugging C.something",str);
}

And this correctly logs "one","two" from the string set.

Afterwards I have the following function:

C.something.add("name");
C.userPreferencesEditor.putStringSet(C.SOMETHING, C.something);
C.userPreferencesEditor.apply(); //or with .commit();

And debugging shows "one","two" and "name". When I restart the app and debug for the first time I only obtain "one" and "two". Any idea on why this happens? tyvm

Upvotes: 2

Views: 48

Answers (1)

sfThomas
sfThomas

Reputation: 1955

This says

Objects that are returned from the various get methods must be treated as immutable by the application.

More specifically:

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

Can you try copying the HashSet you retrieved, adding a new entry to the copy, and saving it in preferences?

BTW - I'd be really curious to know why this is the way it is - not very intuitive...

Upvotes: 2

Related Questions