I'm registering a preference change listener like this (in the onCreate() of my main activity):

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

prefs.registerOnSharedPreferenceChangeListener(
   new SharedPreferences.OnSharedPreferenceChangeListener() {
       public void onSharedPreferenceChanged(
         SharedPreferences prefs, String key) {

         System.out.println(key);
       }
});

The trouble is, the listener is not always called. It works for the first few times a preference is changed, and then it is no longer called until I uninstall and reinstall the app. No amount of restarting the application seems to fix it.

I found a mailing list thread reporting the same problem, but no one really answered him. What am I doing wrong?

share|improve this question
up vote 500 down vote accepted

This is a sneaky one. SharedPreferences keeps listeners in a WeakHashMap. This means that you cannot use an anonymous inner class as a listener, as it will become the target of garbage collection as soon as you leave the current scope. It will work at first, but eventually, will get garbage collected, removed from the WeakHashMap and stop working.

Keep a reference to the listener in a field of your class and you will be OK, provided your class instance is not destroyed.

i.e. instead of:

prefs.registerOnSharedPreferenceChangeListener(
  new SharedPreferences.OnSharedPreferenceChangeListener() {
  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // Implementation
  }
});

do this:

// Use instance field for listener
// It will not be gc'd as long as this instance is kept referenced
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // Implementation
  }
};

prefs.registerOnSharedPreferenceChangeListener(listener);

The reason unregistering in the onDestroy method fixes the problem is because to do that you had to save the listener in a field, therefore preventing the issue. It's the saving the listener in a field that fixes the problem, not the unregistering in onDestroy.

UPDATE: The Android docs have been updated with warnings about this behavior. So, oddball behavior remains. But now it's documented.

share|improve this answer
10  
This was killing me, I thought I was losing my mind. Thank you for posting this solution! – Brad Hein Sep 27 '10 at 1:00
7  
This post is HUGE, thanks a lot, this could have cost me hours of impossible debugging! – Kevin Gaudin Nov 19 '10 at 15:37
16  
A symptom of implementors trying to bee too clever... – Glenn Maynard Jun 5 '11 at 18:45
5  
Great answer, thank you. Definitely should be mentioned in the docs. code.google.com/p/android/issues/detail?id=48589 – Andrey Chernih Nov 25 '13 at 8:15
7  
I wish I could upvote this 1000 times. Mucho thanks man! – ChrisCM Aug 26 '14 at 15:26

As this is the most detailed page for the topic I want to add my 50ct.

I had the problem that OnSharedPreferenceChangeListener wasn't called. My SharedPreferences are retrieved at the start of the main Activity by:

prefs = PreferenceManager.getDefaultSharedPreferences(this);

My PreferenceActivity code is short and does nothing except showing the preferences:

public class Preferences extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // load the XML preferences file
        addPreferencesFromResource(R.xml.preferences);
    }
}

Every time the menu button is pressed I create the PreferenceActivity from the main Activity:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //start Preference activity to show preferences on screen
    startActivity(new Intent(this, Preferences.class));
    //hook into sharedPreferences. THIS NEEDS TO BE DONE AFTER CREATING THE ACTIVITY!!!
    prefs.registerOnSharedPreferenceChangeListener(this);
    return false;
}

Note that registering the OnSharedPreferenceChangeListener needs to be done AFTER creating the PreferenceActivity in this case, else the Handler in the main Activity won't be called!!! It took me some sweet time to realize that...

share|improve this answer
1  
Thank you!!!!!! – RyanS Nov 11 '12 at 17:37

It make sense that the listeners are kept in WeakHashMap.Because most of the time, developers prefer to writing the code like this.

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).registerOnSharedPreferenceChangeListener(
    new OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(
        SharedPreferences sharedPreferences, String key) {
        Log.i(LOGTAG, "testOnSharedPreferenceChangedWrong key =" + key);
    }
});

This may seem not bad. But if the OnSharedPreferenceChangeListeners' container was not WeakHashMap, it would be very bad.If the above code was written in an Activity . Since you are using non-static (anonymous) inner class which will implicitly holds the reference of the enclosing instance. This will cause memory leak.

What's more, If you keep the listener as a field, you could use registerOnSharedPreferenceChangeListener at the start and call unregisterOnSharedPreferenceChangeListener in the end. But you can not access a local variable in a method out of it's scope. So you just have the opportunity to register but no chance to unregister the listener. Thus using WeakHashMap will resolve the problem. This is the way I recommend.

If you make the listener instance as a static field, It will avoid the memory leak caused by non-static inner class. But as the listeners could be multiple, It should be instance-related. This will reduce the cost of handling the onSharedPreferenceChanged callback.

share|improve this answer

this accepted answer is ok, as for me it is creating new instance each time the activity resumes

so how about keeping the reference to the listener within the activity

OnSharedPreferenceChangeListener myPrefListner = new OnSharedPreferenceChangeListener(){
      public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
         // your stuff
      }
};

and in your onResume and onPause

@Override     
protected void onResume() {
    super.onResume();          
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);     
}



@Override     
protected void onPause() {         
    super.onPause();          
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);

}

this will very similar to what you are doing except we are maintaining a hard reference.

share|improve this answer
    
Why you used super.onResume() before getPreferenceScreen()... ? – Yousha Aleayoub Apr 2 '16 at 13:38
    
@YoushaAleayoub, read about android.app.supernotcalledexception it is required by android implementation. – Samuel Apr 4 '16 at 6:46
    
what do you mean? using super.onResume() is required OR using it BEFORE getPreferenceScreen() is required? because I'm talking about the RIGHT place. cs.dartmouth.edu/~campbell/cs65/lecture05/lecture05.html – Yousha Aleayoub Apr 5 '16 at 13:12
    
I remember reading it here developer.android.com/training/basics/activity-lifecycle/…, see the comment in the code. but putting it in tail is logical. but till now I haven't faced any problems in this. – Samuel Apr 6 '16 at 10:43
    
Thanks a lot, everywhere else that I found onResume() and onPause() method they registered this and not listener, it caused error and I could solve my problem. Btw these two methods are public now, not protected – Nicolas Maltais Dec 23 '16 at 18:54

While reading Word readable data shared by first app,we should

Replace

getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);

with

getSharedPreferences("PREF_NAME", Context.MODE_MULTI_PROCESS);

in second app to get updated value in second app.

But still it is not working...

share|improve this answer
    
Android doesn't support accessing SharedPreferences from multiple processes. Doing so causes concurrency issues, which can result in all preferences being lost. Also, MODE_MULTI_PROCESS is no longer supported. – Sam Oct 15 '17 at 3:48
    
@Sam this answer is 3 years old, please so don't down-vote it, if its not working for you in latest versions of android. the time answer were written it was the best approach to do so. – shridutt kothari Oct 18 '17 at 8:45
    
No, that approach was never multi process safe, even when you wrote this answer. – Sam Oct 18 '17 at 9:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.