How Android saves an activity state _android

Source: Internet
Author: User
Tags gettext sqlite sqlite database

The example in this article describes how Android saves activity state. Share to everyone for your reference, specific as follows:

If you want to save information about an activity (for example, a variable of a class instance) without having to share it with other components, you can invoke the Getpreferences method of the activity without specifying a preference name. Access to the returned shared preference is limited to the invoked activity; Each activity supports an unnamed shared preference object.

The following framework code shows how to use the private shared preference of an activity:

protected void Saveactivitypreferences ()
{
//Create or retrieve the activity preferences object.
Sharedpreferences activitypreferences = getpreferences (activity.mode_private);
Retrieve an editor to modify the shared preferences.
Sharedpreferences.editor Editor = Activitypreferences.edit ();
Retrieve the View
TextView Mytextview = (TextView) Findviewbyid (R.id.mytextview);
Store new primitive types in the shared preferences object.
Editor.putstring ("Currenttextvalue", Mytextview.gettext (). toString ());
Commit changes.
Editor.commit ();
}

Saving and restoring instance State

For variables that save an activity instance, Android provides a special way to replace shared preference.

By overriding the activity's Onsaveinstancestate event handler, you can use its bundle argument to hold the value of the instance. The method of saving the data is to use the same get and put method as in the shared preference. After you have finished modifying the bundle, pass it into the handler function of the parent class, as shown in the following code fragment:

private static final String Textview_state_key = "Textview_state_key";
@Override public
void Onsaveinstancestate (Bundle outstate) {
//Retrieve the View
TextView Mytextview = ( TextView) Findviewbyid (R.id.mytextview);
Save its state
outstate.putstring (Textview_state_key,
mytextview.gettext (). toString ());
Super.onsaveinstancestate (outstate);
}

This handler is triggered at the end of the active lifecycle of the activity, but only if it does not end explicitly (that is, the end of the exception). Therefore, it is generally used to ensure consistency of activity status between active lifecycles in a single user session.

If the application is forced to reboot during a session, the saved bundle is passed into the Onrestoreinstancestate and OnCreate methods. The following fragment shows how to update the status of an activity instance by extracting a value from bundle:

@Override public
void OnCreate (Bundle icicle) {
super.oncreate (icicle);
Setcontentview (r.layout.main);
TextView Mytextview = (TextView) Findviewbyid (R.id.mytextview);
String text = "";
if (icicle!= null && icicle.containskey (textview_state_key))
text = icicle.getstring (Textview_state_key) ;
Mytextview.settext (text);


It is important to remember that onsaveinstancestate is invoked only when the activity becomes inactive, but not when the finish is called to close it or when the user presses the Back button.

Save the status of the to-do List activity

At present, every time the to-do list example program restarts, all to-do items are lost and any text entered in the text entry box is cleared. In this example, you will save the state of the to-do list program during the session.

The instance state in the ToDoList activity consists of three variables:

① is a new item being added?

What type of text does the ② have in the New Project entry box?

③ which is the currently selected item?

Using the activity default shared preference, you can save these values and update the UI when the activity restarts.

Later in this chapter, you will learn how to use SQLite to save to-do projects. This example is the first step, demonstrating how to ensure a flawless experience by maintaining the details of the activity instance.

1. Add a static string to use as the preference key.

private static final String Text_entry_key = "Text_entry_key";
private static final String Adding_item_key = "Adding_item_key";
private static final String Selected_index_key = "Selected_index_key";

2. Next, rewrite the OnPause method. Gets the private shared preference of the activity and gets its editor object.

Use the key created in step 1th to store the value of the instance, including whether a new item is being added and any text in the "New Item" entry box.

@Override
protected void OnPause () {
super.onpause ();
Get the Activity preferences object.
Sharedpreferences uistate = getpreferences (0);
Get the preferences editor.
Sharedpreferences.editor Editor = Uistate.edit ();
ADD the UI State preference values.
Editor.putstring (Text_entry_key, Myedittext.gettext (). toString ());
Editor.putboolean (Adding_item_key, addingnew);
Commit the preferences.
Editor.commit ();
}

3. Write a Restoreuistate method that applies the value of the instance recorded in step 2nd when the program is restarted.

Modify the OnCreate method to add a call to the Restoreuistate method in the last section.

@Override public
void OnCreate (Bundle icicle)
{
[... existing onCreate logic ...]
Restoreuistate ();
}
private void Restoreuistate ()
{
//Get the Activity preferences object.
Sharedpreferences settings = getpreferences (activity.mode_private);
Read the UI state values, specifying default values.
String Text = settings.getstring (Text_entry_key, "");
Boolean adding = Settings.getboolean (Adding_item_key, false);
Restore the UI to the previous state.
if (adding)
{
addnewitem ();
Myedittext.settext (text);
}


4. Use the onsaveinstancestate/onrestoreinstancestate mechanism to record the index of the currently selected item. It is saved and applied only when a non-user explicit instruction kills an application.

@Override public
void Onsaveinstancestate (Bundle outstate)
{
outstate.putint (Selected_index_key, Mylistview.getselecteditemposition ());
Super.onsaveinstancestate (outstate);
}
@Override public
void Onrestoreinstancestate (Bundle savedinstancestate)
{
int pos =-1;
if (savedinstancestate!= null)
if (Savedinstancestate.containskey (Selected_index_key))
pos = Savedinstancestate.getint (Selected_index_key,-1);
Mylistview.setselection (POS);


When you run the To-do list program, you should see the UI state saved during the session. However, it is not yet able to save the items in the to-do list-you will add this core functionality later in this chapter.

For more information on Android-related content readers can view the site: "The activity of Android programming skills Summary", "Android View Summary", "Android operation SQLite Database Skills Summary", " Android operation JSON format data tips summary, "Android Database Operation skills Summary", "Android File Operation skills Summary", "Android programming development of SD card Operation Summary", "Android Development introduction and Advanced Course", " Android Resource Operation tips Summary and the "Android Controls usage Summary"

I hope this article will help you with the Android program.

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.