Try to encapsulate your SharedPreferences in some preferences class, similar to this:
class MyPrefs {
private static final String FILENAME = "prefs_filename";
private static final String KEY_SOMETHING = "something";
private SharedPreferences mPreferences;
public MyPrefs(Context context) {
mPreferences = new SharedPreferences(FILENAME, Context.MODE_PRIVATE);
}
public void setSomething(Something value) {
mPreferences.edit().put...(KEY_SOMETHING, value).commit();
}
public Something getSomething() {
return mPreferences.getSomething(key, defaultValue);
}
}
This way we provide clean API for our non-volatile data storage. SharedPreferences
is too low-level, exposing too many details, such as storage file name and it forces us to remember all keys and value types to extract any data. It may work in simple cases, but as soon as your stored data becomes complex, it creates tons of problems. Try storing something like a user profile with few fields or a simple complex number and you'll get the idea. Using raw SharedPreferences
will make your refactoring royal pain. Even simple data format upgrade (like schema update) will quickly become impossible with naked SharedPreferences
.