Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSharedPreferenceChanged called multiple times.... why?

Tags:

android

I have a preference Activity, at first when I chance a preference the onPreferenceChange is triggered once as expected.

However, after some time (going to different activities and such) the onPreferenceChange is called twice.

I see in the debugger that the WeakHashMap for the mListeners is 1 in the beginning and then becomes greater than 1, but not sure why?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPrefs();
    int preferencesResource = 0; // R.xml.preferences;
    preferencesResource = getResources().getIdentifier("pref", "xml",
            getPackageName());
    addPreferencesFromResource(preferencesResource);
    listener = new SharedPreferences.OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences arg0,
                String arg1) {
            // Why is this called once then sometimes twice!!
            Log.i("PreferencesActivity", "OnPreferenceChanged()");
        }
    };
    prefs.registerOnSharedPreferenceChangeListener(listener);
}

protected void onDestroy() {
    super.onDestroy();
    listener = null;
    prefs.unregisterOnSharedPreferenceChangeListener(listener);
    prefs = null;
}

public Preferences getPrefs() {
    if (prefs == null) prefs = new Preferences(this);
    return prefs;
}
like image 406
AndroidPlaya Avatar asked Apr 14 '11 07:04

AndroidPlaya


2 Answers

You've placed unregisterOnSharedPreferenceChangeListener() in onDestroy() and it's not called on all activity restarts.

Look at the activity lifecycle diagram. Conclusion is that proper way to do this is to place registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() in onResume() and onPause() respectively.

like image 101
Andrzej Duś Avatar answered Nov 08 '22 20:11

Andrzej Duś


This isn't for a LiveWallpaper by any chance is it? It sounds to me like you have two instances of the same class running(I.E. The LiveWallpaper itself as well as the preview because you're in settings). If it seems like they happen instantly right on top of each other and there is no delay than most likely you have the same listener running twice.

like image 40
Justin Buser Avatar answered Nov 08 '22 20:11

Justin Buser