Skip to content Skip to sidebar Skip to footer

Best Place To Put Onsharedpreferencechangelistener

I am trying to add a setting to my app. I have added the new setting but I am not sure where to put OnSharedPreferenceChangeListener. I put it in the activity and added a Log.d(),

Solution 1:

The best place according to Android Settings doc would be:

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

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

And you should store the listener in a field variable (or use the Activity object itself - as in the above source code), so that it does not get garbage collected.

I.e. an anonymous class object can't be used as OnSharedPreferenceChangeListener.

Solution 2:

You need to register your listener by invoking setOnPreferenceChangeListener. I'm going to assume that you have an Activity class that extends PreferenceActivity. If so, that is the best place for your listener. You'd write something like this:

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    PreferencemyPreference= findPreference("my_pref");
    myPreference.setOnPreferenceChangeListener(this);
}

Post a Comment for "Best Place To Put Onsharedpreferencechangelistener"