A case study on the method of saving and recovering fragment state in Android development _android

Source: Internet
Author: User

As we all know, similar to activity, Fragment has onsaveinstancestate () callback to save the state.

Inside the fragment, use Onsaveinstancestate to save the data and restore the data in onactivitycreated.

public void onactivitycreated (Bundle savedinstancestate) {
  super.onactivitycreated (savedinstancestate);
  ...
  if (savedinstancestate!= null) {
    //Restore The fragment ' s here
  }} is public

void Onsaveinstancestat E (Bundle outstate) {
  super.onsaveinstancestate (outstate);
  Save The fragment ' s state here
}

However, according to the author's experience, this method is called very not by PU. Fragment creates a completely new View when the screen rotates and returns to the stack (backstack), and the Onsaveinstancestate () method often occurs without being invoked, causing the Fragment state to be lost.

Let's look for solutions through the next examples.

First of all, although there is already a similar onsaveinstancestate method in activity, it obviously does not cover all situations. To put it another way, you can't just rely on the Onsaveinstancestate method to save/restore the state of the view. Here are some case studies.

Case 1: Only one Fragment on the stack, rotate the screen

Screen rotation is the simplest case for testing the save/restore of an instance state. This is easy to handle and you simply need to save something, such as a member variable, and it will also be lost in the onsaveinstancestate when the screen is rotated and restored in onactivitycreated or onviewstaterestored. As shown below:

int somevar;
@Override
  protected void onsaveinstancestate (Bundle outstate) {
  outstate.putint ("Somevar", Somevar);
  Outstate.putstring ("Text", Tv1.gettext (). toString ());
@Override public
void onactivitycreated (Bundle savedinstancestate) {
  super.onactivitycreated ( Savedinstancestate);
  Somevar = Savedinstancestate.getint ("Somevar", 0);
  Tv1.settext (savedinstancestate.getstring ("text"));
}

Does it look good? But it's not all that works. This situation is not being recalled in Onsaveinstancestate, but the view is regenerated. What does that mean? All the things in the UI are gone. Here's the case.

Case 2: Fragmen T in back Stack


when a fragment is returned from the back stack (fragment A is in this case), the fragment a view will follow the fragment lifecycle of the following figure to be created again.

You will see that when fragment returns from the back stack, the Ondestroyview method and the Oncreateview method are recalled. Anyway, obviously in this case the Onsaveinstancestate method is not invoked. The result is that nothing is in the UI and is recreated by default as defined in the Layout XML file.

In any case, a view that is saved by an intrinsic view state, such as a edittext or TextView with Android:freeezetext, can still hold the state of the view because Fragment implements the state save for the inner view, But we developers are not able to capture these events. The only thing we can do is to save the instance state manually in the Ondestroyview method.

@Override public
void Onsaveinstancestate (Bundle outstate) {
  super.onsaveinstancestate (outstate);
  Save state is
@Override public
void Ondestroyview () {
  super.ondestroyview ();
  Save state Here
}

The problem also followed, Ondestroyview does not provide any help to save the instance state to a Bundle, so where should we save these instance states? The answer is Argument, which will be kept with Fragment.

Now the code looks like this:

Bundle savedstate;
  @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate); Restore state here if (!restorestatefromarguments ()) {//running, Initialize something here}} @Ove
  Rride public void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate);
Save state savestatetoarguments ();
  @Override public void Ondestroyview () {Super.ondestroyview ();
Save state savestatetoarguments ();
  private void Savestatetoarguments () {savedstate = SaveState ();
   if (savedstate!= null) {Bundle b = getarguments ();
  B.putbundle ("internalSavedViewState8954201239547", savedstate);
  } private Boolean restorestatefromarguments () {Bundle b = getarguments ();
  savedstate = B.getbundle ("internalSavedViewState8954201239547");
   if (savedstate!= null) {restorestate ();
  return true;
return false; }///////////////////////////////////Restore Instance StaTe here/////////////////////////////////private void Restorestate () {if (savedstate!= null) {//For Example/
  /tv1.settext (savedstate.getstring ("text")); 
  }////////////////////////////////Save Instance state here//////////////////////////////private Bundle savestate () {
  Bundle state = new Bundle ();
  For Example//state.putstring ("text", Tv1.gettext (). toString ());
return state;
 }

You can easily save your fragment state in SaveState, and restore state in restorestate. It looks a lot better now. We're almost done, but there's a weird situation.

Case 3: Rotate screen two times when more than one fragment in the back stack

When you rotate the screen once, the onsaveinstancestate will be recalled, and as we expect, the UI state will be saved. But when you rotate the screen more than once, the above code can cause the application to crash. The reason is that although the Onsaveinstancestate method is invoked when you rotate the screen, the fragment in the back stack completely destroys the view until you browse back to the original fragment before recreating it. So, once you rotate the screen again, there is no view to save the state. When you try to access a view that does not exist, savestate () will cause the NullPointerException to crash the application.

The method is to check whether the view exists in the fragment. If it exists, it is saved, if it does not exist, it is in the Argument savedstate do not need to be saved and then returned. Or we don't even have to do anything, because we've done it in argument.

private void Savestatetoarguments () {
  if (GetView ()!= null)
   savedstate = SaveState ();
  if (savedstate!= null) {
   Bundle B = getarguments ();
   B.putbundle ("savedstate", savedstate);
  }

Ha, it's all settled now!

Fragment Final Template
The following are the fragment templates that I now use for my work.

Import Android.os.Bundle;
Import android.support.v4.app.Fragment;
Import Android.view.LayoutInflater;
Import Android.view.View;

Import Android.view.ViewGroup;

Import COM.INTHECHEESEFACTORY.THECHEESELIBRARY.R;
 /** *created by Nuuneoi on 11/16/2014.

  * * public class Statedfragment extends Fragment {Bundle savedstate;
  Public Statedfragment () {super (); @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate
    ); Restore state here if (!restorestatefromarguments ()) {//The Initialize something here Onfirst
    Timelaunched ();
    } protected void Onfirsttimelaunched () {} @Override public void Onsaveinstancestate (Bundle outstate) {
    Super.onsaveinstancestate (outstate);
  Save state savestatetoarguments ();
    @Override public void Ondestroyview () {Super.ondestroyview ();
  Save state savestatetoarguments (); }

  ///////////////Don ' t touch!!
    private void Savestatetoarguments () {if (GetView ()!= null) savedstate = SaveState ();
      if (savedstate!= null) {Bundle b = getarguments ();
    B.putbundle ("internalSavedViewState8954201239547", savedstate);
  }//////////////////////Don ' t touch!!
    Private Boolean restorestatefromarguments () {Bundle b = getarguments ();
    savedstate = B.getbundle ("internalSavedViewState8954201239547");
      if (savedstate!= null) {restorestate ();
    return true;
  return false; }///////////////////////////////////Restore Instance state here/////////////////////////////////private Voi
      D restorestate () {if (savedstate!= null) {//For Example//tv1.settext (savedstate.getstring ("text"));
    Onrestorestate (savedstate); } protected void Onrestorestate (Bundle savedinstancestate) {}////////////////////////////////Save Instance state this//////////////////////////////private Bundle savestate () {Bundle state = new Bundle ();
    For Example//state.putstring ("text", Tv1.gettext (). toString ());
    Onsavestate (state);
  return state;

 } protected void Onsavestate (Bundle outstate) {}}

If you use this template, simply inherit the class statedfragment and then save things in Onsavestate () and restore them in onrestorestate (). The code above will do the rest for you, and I'm sure it covers the possibilities I've known.

Setretaininstance can help developers process member variables when layout changes (e.g., screen rotation) and you may notice that I have not set Setretaioninstance to true. Keep in mind that this is my purpose because setretaininstance (true) does not cover all cases. The main reason is that you can't save the nested fragment that you use frequently back and again. So my advice is not to save the instance unless you're 100% sure this fragment will not be used for nesting.

Usage:
Good news. This blog statefragment now joins a very easy to use library and is now published on Jcenter. Now you can simply add a dependency to the Build.gradle file in your project. As shown below:

dependencies {
  compile ' com.inthecheesefactory.thecheeselibrary:stated-fragment-support-v4:0.9.1 '
}

Inherits Statefragment, then saves the state in Onsavestate (Bundle outstate) and restores the state in Onrestorestate (Bundle saveinstancestate). If you want to do something on the first boot of fragment, you can also overwrite the onfirsttimelaunched () method (which will not be invoked later).

public class Mainfragment extends Statedfragment {

  ...

  /**
   * Save Fragment ' s state
   -here
  /@Override protected void Onsavestate (Bundle outstate) {
    Super.onsavestate (outstate);
    For example:
    //outstate.putstring ("text", Tvsample.gettext (). toString ());

  /**
   * Restore Fragment ' s state here
  /@Override
  protected void Onrestorestate (Bundle Savedinstancestate) {
    super.onrestorestate (savedinstancestate);
    For example:
    //tvsample.settext (savedinstancestate.getstring ("text"));
  }

  ...

}

End

Finally, do not ignore the problem of state preservation, in the memory is not enough or more stringent system constraints on top of the machine, there may be fragment or activity is recycled, such as frequent photos after the return of the app, but the app inside the data is emptied, more common is the rotating screen, So keep the data you need.

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.