简体   繁体   English

OS杀死活动后,片段savedInstanceState不为null

[英]Fragment savedInstanceState not null after activity killed by OS

I have a fragment which saves the state via setRetainInstance(true) . 我有一个片段,它通过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 . 有时,应用程序崩溃并显示NullPointerException我的mData突然变为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) ). 一段时间后,操作系统杀死了ActivityFragment (尽管setRetainInstance (true) )。 Thus creates a new object of my fragment where mData initialized by null . 因此创建了我的片段的新对象,其中mDatanull初始化。 But savedInstanseState not equals to null. 但是savedInstanseState不等于null。 Thus the new fragment skips initialization and attempts to call refresh(View) on the null reference. 因此,新片段将跳过初始化,并尝试在null引用上调用refresh(View)

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? 我的问题:当操作系统onActivityCreated(savedInstanceState)活动(当应用程序不在屏幕上时)并在返回后重新创建时,我的代码片段中的onActivityCreated(savedInstanceState)方法中的savedInstanseState变量将包含什么?

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). setRetainInstance(布尔值保留)控制是否在Activity重新创建期间保留片段实例(例如,从配置更改中保留)。 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). 所以我认为,当您折叠活动时,视图将被破坏,实例数据(setReetainInstance值)被保存在捆绑包中(在加载时使saveInstanceState!= null)。 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. 但是,当您加载活动时(因为之前将keepInstance设置为true),onCreate()不会被调用,并且由于saveInstanceState!= null和mData == null会导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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