Android: Data --- SharedPreferences
-
This is a way to save small ammounts of data.
-
Often associated with the concept of User Preferences --i.e. saved login, or specified text color, etc.
-
Usefull when you want to save only a little information and don't want overhead of File I/O.
-
Saves as name=value pairs in an xml file associated with the specified application package. (default is application_packagename_preferences.xml )
-
Uses android.content.SharedPreferences
-
Limitation --- only shares data (name/value pairs) across classes in the same Package!!!
What to do
Step 1: somehow get the data in name/value pairs you want to store
Step 2: Inside Activity class use it's getSharedPreferences("<packageName>_preferences", Mode) to get instance of SharedPreferences class, lets call it appPrefs
//inside your ACTIVITY class
SharedPreferences appPrefs = getSharedPreferences("apps_packagename.whatever_preferences", MODE_PRIVATE);
// the above call will create the xml file apps_packagename.whatever_preferences.xml if it does not exist to store dataNOTE: getSharedPreferences(String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.NOTE: MODE_PRIVATE means the xml prefrence file that will get created by this method to store the name/value pairs can only be edited by this application.
Step 3: Use aSharedPreferences to grab any already stored value for a particular name
- COMMAND TO GET DATA: appPrefs.getString("name", "");
- or getInt, getLong ,etc. See API
Step 4: If you want to store new name/value pairs or modify the values of an already stored pair -----
Get instace of android.content.SharedPreferences.Editor by calling appPrefs.edit();
android.content.SharedPreferences.Editor prefsEditor = appPrefs.edit();
Step 5: Use android.content.SharedPreferences.Editor to modify the current Preferences, using Editor.put*("name","value")
- COMMAND TO PUT DATA: prefsEditor.putString("name","value");
- or putInt, putLong ,etc. See API
- COMMAND TO COMMIT TO FILE and puts,etc: prefEditor.commit(); //until do this file not altered.
- COMMAND TO CLEAR DATA: prefsEditor.clear(); //clears all stored data
Example using Android PreferenceActivity with SharedPreferences for storage
NOTE: this example does not use the default filename package_preferences.xml and instead gives its own name for the xml file