Changes on a string set in shared preferences not posted to onSharedPreferenceChanged

Viewed 53

If i update a string set to shared preferences i do not get a callback to the registered onSharedPreferenceChanged method. Other updates (non string sets) will notfiy the method above.

Listener code:

public class MyFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener
{
    public void onCreatePreferences (Bundle bundle, String s)
    {
        ...
        SharedPreferences preferences = <preferences>;
        preferences.registerOnSharedPreferenceChangeListener (this);
        ...
    }

     public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key)
     {
         if (key.equals ("stringset-key"))
         {
             ... code to execute ...
         }
     }
}

Update activity:

public class MyActivity extends AppCompatActivity
{
    ...
    SharedPreferences preferences = <preferences>;
    Set<String> values = preferences.getStringSet ("stringset-key", null);

    values.add ("new string");

    SharedPreferences.Editor pref = preferences.edit ();
    pref.putStringSet ("stringset-key, values);
    pref.commit ();
    ...

MyFragment is used in MyActivity.

The only working solution i found so far is to remove the item (pref.remove + pref.commit) before setting the updated value.

1 Answers

I was having the same issue as you are and it seems that if you use the same Set reference SharedPreferences does not detect the change.

A related bug previously reported: https://issuetracker.google.com/issues/36943216

It seems the only way to go is removing and adding the set back as you did.

Related