Preferences
Preference works as data persistence. We have other choices to save data in Android.
One is creating setting file, the other is using database(SQLite3).
Compare to other choices, preference is easy to use.
Preference
Preference is key-value store. These data may be written under file.
We need to manage only key, value. 🙂
How to
SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(this); // Read boolean key = spf.getBoolean("key", false); // Write spf.edit().putBoolean("key", true).commit();
In this case, the argument of getDefaultSharedPreferences is Activity(Context)
commit is same as database commit.(save immediately)
Key-Value Type
There are several key-value type of preference
Float, Int, Long, String, Set
Type | Get | Set |
---|---|---|
float | getFloat(String key, float defValue) | putFloat(String key, float value) |
int | getInt(String key, int defValue) | putInt(String key, int value) |
long | getLong(String key, long defValue) | putLong(String key, long value) |
boolean | getBoolean(String key, boolean defValue) | putBoolean(String key, boolean value) |
String | getString(String key, String defValue) | putString(String key, String value) |
Set<String> | getStringSet(String key, Set<String> defValue) | putStringSet(String key, Set<String>) |
See get method, all method has default value, if you are missing to set value, you can get this value.