迁移到 AndroidX 应用程序后,尝试调用 androidx.fragment.app.FragmentManagerImpl.isDestroyed() 在空引用上崩溃

2022-09-04 23:55:26

完整的堆栈仅包含安卓核心代码:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.fragment.app.FragmentManagerImpl.isDestroyed()' on a null object reference
    at androidx.fragment.app.Fragment.performDetach(Fragment.java:2844)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1033)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1237)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:434)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2075)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1865)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1820)
    at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1726)
    at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

在替换主活动中的片段时会发生这种情况:

Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

答案 1

我在myFragment.onDetach中发现了一段导致这种情况的代码:

这是在ViewPager中使用选项卡时获取错误“Java.lang.IllegalStateException Activity已被销毁”的解决方法

        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

现在,在androidx中,不需要此解决方法。


答案 2

在我的模块的等级中,我通过恢复来修复它

implementation 'androidx.appcompat:appcompat:1.1.0-beta01'

implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'

(上面对childFragmentManager的东西的回答没有帮助。


推荐