Brad Hein Brad Hein - 1 year ago 208
Android Question

onSharedPreferenceChanged not fired if change occurs in separate activity?

I've implemented

in my main activity.

If I change the preferences in the main activity, my event fires.

If I change the preferences through my preferences screen (
) my event does NOT fire when preferences are changed (because it's a separate activity and separate reference to sharedPreferences?)

Does anybody have a recommendation of how I should go about overcoming this situation?


EDIT1: I tried adding the event handler right in my preference activity but it never fires. The following method gets called during onCreate of my preference activity. When I change values, it never prints the message (
is a wrapper for

private void registerChangeListener () {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener () {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
msg (" ***** Shared Preference Update ***** ");
Intent i = new Intent();
i.putExtra("KEY", key);


// TODO: fire off the event

Answer Source

The OnSharedPreferenceChangeListener gets garbage collected in your case if you use an anonymous class.

To solve that problem use the following code in PreferenceActivity to register and unregister a change listener:

public class MyActivity extends PreferenceActivity implements
    OnSharedPreferenceChangeListener {

protected void onResume() {
    // Set up a listener whenever a key changes

protected void onPause() {
    // Unregister the listener whenever a key changes

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) 
  // do stuff

Furthermore be aware that the listener only gets called if the actual value changes. Setting the same value again will not fire the listener.

see also SharedPreferences.onSharedPreferenceChangeListener not being called consistently

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download