Android Apidemos Example Resolution (9) App-activity-persistent State

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.