Thứ Ba, 29 tháng 12, 2009

Android: SharedPreferences

Shared Preferences
SharedPreferences let you save groups of key/value pairs of primitive data as named preferences. SharedPreferences is a lightweight mechanism to store a known set of values such as: user preferences, configuration, application settings...
The data which had created by SharedPreferences can be shared between applicaton components running in the same "Context".
Creating and Saving SharePreferences

//Define SharePreference Name
private static final String STRING_SHAREREF_NAME_USERREF = "USER REFERENCES";
//SharedPreferences object
private SharedPreferences mShareRefs = null;
//Create and save
protected void savePreferences() {
//get value from ui
boolean bAutoUpdate = mCbxAutoUpdate.isChecked();
int iFrequency = mSpinnerFrequency.getSelectedItemPosition();
int iMinMag = mSpinnerMinMagtitude.getSelectedItemPosition();

//Create SharedPreferences object
mShareRefs = getSharedPreferences(STRING_SHAREREF_NAME_USERREF,
Activity.MODE_PRIVATE);

//update to Preference by editor interface.
Editor editor = mShareRefs.edit();
editor.putBoolean(STRING_SHAREREF_USERREF_AUTOUPDATE, bAutoUpdate);
editor.putInt(STRING_SHAREREF_USERREF_FREQUENCYUPDATE, iFrequency);
editor.putInt(STRING_SHAREREF_USERREF_MINMAG, iMinMag);
editor.commit();
}
Notes:
- If you want to save information that doesn't need to be shared with others component, you can call Activity.getPreferences(Mode) without a specifying preference name.
(Activity).getPreferences(Activity.MODE_PRIVATE);

Retrieve the saved values:
SharedPreferences object offers some method to get persist data (type boolean, String, int, Long, ..):
  • getBoolean(..);
  • getInt(..);
  • getString(..);
  • ...


Ref:
- Pro Android June 2009
- Profession Android Application Development.

Không có nhận xét nào:

Đăng nhận xét