-
Notifications
You must be signed in to change notification settings - Fork 12
Use SharedPreferences to Persist simple data
rutura edited this page Apr 17, 2017
·
1 revision
- Api level 1
- SharedPreferences give you a simple way to store simple data across configuration changes or app restarts.
- Get a prefereces object that is tied to an activity:
SharedPreferences formStore;
...
//Retrieve or create the preferences object
formStore = getPreferences(Activity.MODE_PRIVATE);
- Get a preference object you may use across activities:
public static final String PREF_NAME = "myPreferences";
....
mPreferences = getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE);
- Retrieve data from prefs and apply it to a ui component:
@Override
public void onResume() {
super.onResume();
//Restore the form data
email.setText(formStore.getString("email", ""));
message.setText(formStore.getString("message", ""));
age.setChecked(formStore.getBoolean("age", false));
}
- Modify the data in SharedPrefs:
SharedPreferences.Editor editor = formStore.edit();
editor.putString("email", email.getText().toString());
editor.putString("message", message.getText().toString());
editor.putBoolean("age", age.isChecked());
editor.commit();