简体   繁体   中英

Fragment savedInstanceState not null after activity killed by OS

I have a fragment which saves the state via setRetainInstance(true) . This is my fragment's very simplified code:

public class MyFragment extends Fragment {
  private SomeData mData;

  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

  @Override
  public void onActivityCreated(@Nullable Bundle savedInstanceState) {
      if (savedInstanceState == null) {
        mData = new SomeData(getView());
      } else {
        mData.refresh(getView());
      }
      // More awesome code
    }
  }
}

Sometimes the app crashes with NullPointerException - my mData suddenly becomes null . This happens when I fold the application and return after some time.

I have some theory. After a while OS kills the Activity and the Fragment (despite setRetainInstance (true) ). Thus creates a new object of my fragment where mData initialized by null . But savedInstanseState not equals to null. Thus the new fragment skips initialization and attempts to call refresh(View) on the null reference.

My question: What will contain the savedInstanseState variable in the onActivityCreated(savedInstanceState) method in my snippet when OS kills the activity (when app not on the screen) and recreate after return?

Not sure about the answer fully but here it is What I can guess

setRetainInstance (boolean retain) Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack.

So I think that When you fold the activity the views get destroyed and instance data (setReetainInstance value)is saved in the bundle ( making savedInstanceState != null while loading). However, when you load the activity (since previously the retainInstance was set to true) onCreate() does not get called and since savedInstanceState != null and mData == null you get the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM