Incorporating Shared Preference Technology into Your Android Applications
- Retrieving and Reading Shared Preferences
- Storing and Updating Shared Preferences
- Creating Preferences Resources Files
- Using the <em>PreferenceActivity</em> Class
Mobile applications often allow the user to control or personalize certain features, application behaviors, and display details. These settings, or preferences, usually need to be stored persistently by the application. Not only does the Android SDK provide a simple means for storing and retrieving these preferences, called shared preferences, it also provides a straightforward means for developers to create consistent user interfaces for the user to manage these preferences.
Retrieving and Reading Shared Preferences
Android application preferences are stored in internally-managed XML files. These structured files hold name-value pairs of preferences in a variety of types. Preference files are private to the application and cannot be shared across applications. In addition to the default preferences, shared preferences can be divided into named groups (in separately named files).
Working with Android shared preferences programmatically is easy. An activity can create or access its private shared preferences data through the SharedPreferences class (android.content.SharedPreferences). To retrieve a suitable instance of the SharedPreferences object, you must call the getSharedPreferences() method of the Context object (android.content.Context) associated with your activity. This method has two parameters: the preference group name and the access mode (similar to regular file access modes). The following line of code is a typical method call for retrieving an instance of the SharedPreferences object from within an Activity class:
SharedPreferences settings = getSharedPreferences("app_prefs", 0);
You can then use the SharedPreferences object to read specific preference values using various getter methods. For example, some of the popular getter methods include: getBoolean(), getFloat(), getInt(), and getString() which retrieve a Boolean value, float value, integer value, and a string value, respectively. The key of the values must be known. All getter methods allow a default value to be passed in so the returned object always has a valid value. If the key is not known, the SharedPreferences class contains a getAll() method for retrieving all of the stored values in that preference group. The following code demonstrates reading some values:
boolean someFlag = settings.getBoolean("some_flag", false); String someString = settings.getString("some_string", "");