Android – How to handle Android onSharedPreferenceChanged without nested IF ELSE statement

androidif statement

I have an Activity that implements a listener for my Shared Preferences, so when the user pulls up the FragmentPrefs and changes a value onSharedPreferenceChanged(SharedPreferences prefs, String key) is called, great.

SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    registerPreferenceListener();
}

private void registerPreferenceListener()
{
    listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {

    Debug.out("LISTENING! - Pref changed for: " + key + " pref: " +
    prefs.getString(key, null) );
      }
    };

    prefs.registerOnSharedPreferenceChangeListener(listener);
}

The problem is I'm trying to find a way to handle the event of the changed preference gracefully, without developing a bad smell in the code.

I have quite a few preferences that need to be managed, so having a nested IF ELSE statement is going to get long and tedious. I've thought about implementing polymorphism, that would work fine but I would still need an if/else to decide on which implementation of the class to call.

A switch might have been better as I could reference the R.string.pref_name, although the changedPref method uses a String as the key identifier.

Am I over complicating things, or am I missing soemthing trivial?

Thanks.

Best Answer

It isn't a nested IF-ELSE. It is just a normal IF-ELSE construction that you use when you need to evaluate a String parameter. Nothing wrong with that. Anything else is defnitely over-complicated.

if (key.equals(PREFS_KEY_A)) {
    ...
} else if (key.equals(PREFS_KEY_B)) {
    ...
} else if (key.equals(PREFS_KEY_C)) {
    ...
}