SharedPreferences is a framework of APIs for storing persistent key-value data on a user's device across multiple sessions. When a user closes an app and later reopens it the SharedPreferences data can be read and used in code. For example, in a game app you can store the user's high score.
Note: A user can manually delete the stored data by doing the following:
Settings –> Applications –> Manage Applications –> Clear Data.
Each SharedPreferences file can hold several different data types (e.g. ints, strings, booleans).
You can read, write, and delete shared preferences data.
To get a SharedPreferences object use one of these methods:
getPreferences(int operating mode) // For activity-specific shared preferences Operating mode: MODE_PRIVATE
// For using shared preferences across activities.
getDefaultSharedPreferences(Context context)
You can use more than one SharedPreferences file by supplying a file name.
getSharedPreferences(String filename, int operating mode)
See the official Android example here:
http://developer.android.com/reference/android/app/Activity.html
Note: You need an editor to make changes to the shared preferences:
SharedPreferences.Editor editor = sharedPref.edit();
In the Official Android code example below mCurViewMode (current view mode) is assigned one of the two static final ints declared at the top of the activity.
public class CalendarActivity extends Activity {
static final int DAY_VIEW_MODE = 0;
static final int WEEK_VIEW_MODE = 1;
private SharedPreferences mPrefs;
private int mCurViewMode;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mPrefs = getSharedPreferences(); // Appears to be a bug in the official Android documentation. I describe the bug here: https://sites.google.com/site/myrononmobileapps/reference-material/bugs
// Read from mPrefs using Key("view_mode")/Default value(DAY_VIEW_MODE).
mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
//Write to shared preferences using key and new value.
ed.putInt("view_mode", mCurViewMode);
ed.commit();
}
}
How to clear shared preferences:
ed.clear();
ed.commit();
How to remove an arbitrary item:
Similar to clear, but enter the key for the item.
ed.remove("Key");
ed.commit();
See also:
http://developer.android.com/training/basics/data-storage/shared-preferences.html
http://developer.android.com/reference/android/content/SharedPreferences.html