Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

registerOnSharedPreferenceChangeListener() approaches comparison

In some code that I am maintaining I noticed two different ways to register a shared preference change listener:

(1) The straightforward approach, in which the class containing the registered member function implements SharedPreferences.OnSharedPreferenceChangeListener.

preferences.registerOnSharedPreferenceChangeListener(mImageView);

(2) The indirect approach, in which the the class that could have contained the registered member function, prefers not to implement SharedPreferences.OnSharedPreferenceChangeListener for some reason, and instead opts for defining and instantiating a whole new class dedicated only for this listener:

SharedPreferences.OnSharedPreferenceChangeListener mPreferencesListener = 
  new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
      // do here what's needed to do
    }
  };


....

preferences.registerOnSharedPreferenceChangeListener(mPreferencesListener);

Both work well but now I am wondering: Is one approach preferable over the other?

Are there circumstances in which only one of these 2 approaches could actually be used?

like image 459
ateiob Avatar asked Nov 04 '22 17:11

ateiob


1 Answers

This is up to implementation, in terms of maintainability some people may found one or other way better for their intentions, some people just go further thinking of readability, natural medicine, etc.

In the other hand of course you may want to prevent any leak and garbage collection issues, said if member created mPreferencesListener is accessing any of the enclosing instance methods you may run in some issues, as a good citizen you should unregister your listeners after you know that you will not be using them (e.g. onPause, onDestroy, etc.) and opt for static inner classes instead of member inner classes and be cautious when anonymous and local inner clases access enclosing instance methods/properties.

Finally is worth to mention that as for now SharedPreferencesImpl uses a WeakHashMap for its listeners.

like image 104
eveliotc Avatar answered Nov 08 '22 15:11

eveliotc