1

In my code I do

String name = ...
SharedPreferences prefs = ...

Set<String> servers; // = new HashSet<String> ();
SharedPreferences.Editor edit = prefs.edit ();
servers = prefs.getStringSet ("serverlist", new HashSet<String> ());
servers.add (name);

edit.putStringSet ("serverlist", servers);
edit.apply ();

The registered listener looks like this

public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key)
{
    if (key.equals ("serverlist"))
    {
        ...
    }
}

On changes to preference the listener is never called. Only if i remove the preference, commit/apply it (required) and store it again the listener gets called:

edit.remove ("serverlist");
edit.apply ();
edit.putStringSet ("serverlist", servers);
edit.apply ();

Changes on simple properties (String, Boolean, ...) are properly signalled to the listener.

Am I doing something wrong?
Or - is that a known issue?

humba
  • 31
  • 3
  • check https://stackoverflow.com/questions/3799038/onsharedpreferencechanged-not-fired-if-change-occurs-in-separate-activity and https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener – Developer Mar 06 '19 at 07:18
  • same happens to me. It has nothing to do with weak reference. I have the same listener, it gets called when the key references anything except a stringset – usernotnull Jul 22 '19 at 16:41
  • The links above don't help. They did not address the StringSet property. The only solution (workaround) i found so far is to delete the shared preference, apply the changes and set the (previously saved) values to the preference again. This fires the call to onPreferenceChanged afterwards. – humba Jul 23 '19 at 17:58

0 Answers0