Android provides a variety of ways to store data, the simplest of which is to use shared Preferences. Shared Preferences can store key/value pairs, shared Preferences support Access Boolean, float, long, Integer, string, most commonly used shared preference S is used to store some application preferences. Another approach is to use Onsaveinstancestate (), which is especially useful for saving UI state.
app->activity->persistent State uses a shared preferences to maintain part of the UI status (TextView value).
Create or modify a shared Preferences, using the Getsharedpreferences (String name, int mode) method. Shared Preferences is used to share some data between different activity of a single application and cannot be used to share data between different application.
Sharedpreferences.editor used to add data to shared preferences: Editor.putxxx (Key,value)
protected void OnPause () {
super.onpause ();
Sharedpreferences.editor Editor = getpreferences (0). Edit ();
Editor.putstring ("Text", Msaved.gettext (). toString ());
Editor.putint ("Selection-start", Msaved.getselectionstart ());
Editor.putint ("Selection-end", Msaved.getselectionend ());
Editor.commit ();
}
Read shared Preference:pref.getXXX (key)
protected void Onresume () {
super.onresume ();
Sharedpreferences prefs = getpreferences (0);
String Restoredtext = prefs.getstring ("text", null);
if (Restoredtext!= null) {
msaved.settext (restoredtext, TextView.BufferType.EDITABLE);
int selectionstart = Prefs.getint ("Selection-start",-1);
int selectionend = Prefs.getint ("Selection-end",-1);
if (SelectionStart!=-1 && selectionend!=-1) {
msaved.setselection (SelectionStart, selectionend);
}
}
}
Persistent state demonstrates how to use shared preferences to keep edittext content when an activity recovers. A more general approach is to use onsaveinstancestate.