FragmentManager NullPointerException when trying to commitAllowingStateLoss

馋奶兔 提交于 2019-12-04 03:47:21

The FragmentManager manages all Fragments at the Activity level, and their lifecycle will be tied to that parent Activity. The child Fragment manager manages all Fragments at the Fragment level, and their lifecycle will be tied to that parent Fragment.

So for your phone architecture, add your InnerFragment to your Activity using getFragmentManager(). When the Activity destroys for good (via back button / finish()), the FragmentManager will destroy and release the InnerFragment for you.

For your tablet architecture, add your InnerFragments to your Fragment using getChildFragmentManager() (in the latest support library). When the Fragment destroys for good, the FragmentManager will destroy and release the InnerFragments for you.

You should not have to manage releasing and destroying your Fragments yourself. I'd recommend logging the lifecycle events of your Activities and Fragments so you can watch them go through their states and ensure correct behavior.

The NullPointerException is caused by the fact that Activity's Handler is unset from the FragmentManager, so a "solution" that will prevent the crash is the following:

public void onDestroy(){
        super.onDestroy();
        try {
            Field mActivityField = getFragmentManager().getClass().getDeclaredField("mActivity");
            mActivityField.setAccessible(true);
            mActivityField.set(getFragmentManager(), this);

            Field mPendingActionsField = getFragmentManager().getClass().getDeclaredField("mPendingActions");
            mPendingActionsField.setAccessible(true);
            mPendingActionsField.set(getFragmentManager(), null);


            Field f = Activity.class.getDeclaredField("mHandler");
            f.setAccessible(true);
            Handler handler = (Handler) f.get(this);
            handler.close();
        } catch (Throwable e) {

        }
}

CASE: When you need to call Fragment(Child fragment) from another Fragment(Parent Fragment)

always use getChildFragmentManager() instead of getFragmentManager inside your Parent Fragment.

Read documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!