Is it a good idea/practice to put static shared preferences editor in a utility class so I can call it whenever needed? The method in the utility class would look like this:
public static SharedPreferences.Editor editor (Context context){
final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPrefs.edit();
}
and use it like this in different classes:
Utility.editor(mContext).putBoolean(categoryId, true);
Utility.editor(mContext).apply();
At least I would't say it's a bad idea.
But here is an even better idea: abstract away the Android specific details and create a clean, readable interface for storage access that fits your domain.
e.g:
interface UserSettings {
void setAutoReloadEnabled(boolean enabled);
boolean isAutoReloadEnabled();
...
}
and then implement it using SharedPreferences
class SharedPreferencesUserSettings implements UserSettings {
final SharedPreferences sharedPrefs;
public SharedPreferencesUserSettings(Context ctx) {
sharedPrefs = ...;
}
@Override void setAutoReloadEnabled(boolean enabled) {
sharedPrefs.editor().putBoolean("...", enabled).commit();
}
...
}
This gives you more readable code and you can actually provide a stub/mock implementation in your tests! If the API of SharedPreferences should change (or when you want to move from using commit
to apply
or vice-versa, or changing the Tags you used for the preferences) you only have to change it in one File, not everywhere in your code.
But there is more: if you should later decide that SharedPreferences
were actually a bad choice, you can switch the implementation to use e.g. a . SQLite Database or ObjectBox instead. Again, without changing the rest of the code.
Needless to say that this might be overkill (aka over-engineering) in certain situations, but in bigger projects this pays out pretty fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With