Reputation: 2433
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.
Upvotes: 1
Views: 5671
Reputation: 95578
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)) {
...
}
Upvotes: 2
Reputation: 4157
nothing wrong with if/else.. and I'm not sure you can escape it. after all, you need to check which item is coming. Polymorphism might look nicer but remember that creating objects in Android is more expensive than on the desktop. So sometimes it's worth the ugly code for the performance (note: unless you can use static methods and avoid new).
Upvotes: 1