How to use Shared Preferences in Android ?
Android provides several options for developers to save persistent application data. The solution you choose must depend on your specific needs.
In this article, we are interested in Shared Preferences that let you to store private primitive data in key-value pairs.
Entry Point of this solution is SharedPreferences class. It provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. SharedPreferences can be used to save any primitive data :
Stored data will persist across user sessions.
To get a SharedPreferences object in an application, 2 methods are provided :
- getSharedPreferences() that must be used if you need multiple preferences files identified by name, which is specified in first parameter.
- getPreferences() that must be used if you need only one preferences file for your activity. Because, this will be the only file there is no need to supply a name.
1. Save a value
Once the SharedPreferences object is got, you must call edit() method to access the SharedPreferences.Editor object. Then, you can put your value thanks to dedicated method by primitive type. For example, for boolean you can call putBoolean(…).
To persist values setted in editor instance, you must commit thanks to a call to commit() on editor instance.
Code is like this :
String PREFS_NAME = "Your pref name ..."; SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("enableShake", enableShake); editor.commit();
2. Retrieve a value
To retrieve stored value, this is very simple :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); boolean enableShake = settings.getBoolean("enableShake", false);
Like you can see, use shared preferences is very simple and this API offers you a powerful way to store primitive data through key-value pairs.