android onCreate FragmentManager.getFragment空指针异常

时间:2017-01-11 19:41:28

标签: android android-fragments

我有一个viewPager,在另一个片段中有3个片段。

目前,我希望获得托管片段上3个片段的引用,因为我需要偶尔调用它们上的一些方法。

所以我使用了putFragment和getFragment来保存/恢复这些片段。

现在,由于某种原因,我得到一个空指针异常 当我调用f1 = fm.getFragment(savedInstanceState, KEY_1);

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:667)
at com.demo.android.view.MainFragment.onCreate(MainFragment.java:137)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        FragmentManager fm = this.getChildFragmentManager();
        f1 = fm.getFragment(savedInstanceState, KEY_1);
        f2 = fm.getFragment(savedInstanceState, KEY_2);
        f3 = fm.getFragment(savedInstanceState, KEY_3);
    }
    if (f1 == null)
        f1 = FragmentBuilder.builder().build();
    if (f2 == null)
        f2 = FragmentBuilder.builder().build();
    if (f3 == null)
        f3 = FragmentBuilder.builder().build();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    FragmentManager fm = this.getChildFragmentManager();
    fm.putFragment(outState, KEY_1, f1);
    fm.putFragment(outState, KEY_2, f2);
    fm.putFragment(outState, KEY_3, f3);
}

0 个答案:

没有答案