views:

176

answers:

2

I've implemented onSharedPreferenceChanged 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 (PreferenceActivity) 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?

Thanks!

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 (msg() is a wrapper for Log.d).

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);
            i.setAction("com.gtosoft.dash.settingschanged");

            sendBroadcast(i);

            // TODO: fire off the event
        }
    });
}
A: 

Why don't you just add a onSharedPreferenceChanged in the rest of the activities where the preferences could change?

Cristian
You mean like define onSharedPreferenceChanged right in my settings activity? I did and it's not firing.
Brad Hein
For the record, the problem was caused by the garbage collector reclaiming my event handler. I had to create a global member reference to the event handler.
Brad Hein
+1  A: 

I use the following code in my PreferenceActivity to register (and unregister) a change listener:

@Override
protected void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    // Unregister the listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
}

maybe that helps...

see also http://stackoverflow.com/questions/2542938/sharedpreferences-onsharedpreferencechangelistener-not-being-called-consistently/3104265#3104265

pivotnig
Oh man you rock! How tricky!!! My onsharedpreferencelistener was being garbage collected! So per your link, I created a long term reference (global member variable) to it and voila, it works great!
Brad Hein