android-清除backstack产生NullPointerException

android-clearing backstack generates NullPointerException

我的应用程序中有 4 个片段:ABCD。首先,将片段 A 的一个实例添加到 activity,而不添加到后台堆栈。然后用户可以动态导航到无限数量的片段。假设这种情况:

            addToBackstack    addToBackstack    addToBackstack    addToBackstack
========> A ==============> B ==============> D ==============> D ==============> C

其中一些转换也包含共享元素,例如从 B 到 D:

getActivity().getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.fragment_holder, D.newInstance(bundle), TAG)
.addSharedElement(view, name)
.addToBackStack(null)
.commit();

现在我需要将用户从最后一个片段直接带到第一个片段 (A)。所以我试过了:

getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

效果很好,但并不总是。有时(我无法找到肯定会导致异常的确切场景)它会使应用程序崩溃并显示以下日志:

2021-07-11 00:53:45.623 14155-14155/app.android.xxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.android.xxx, PID: 14155
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
    at androidx.fragment.app.FragmentTransition.captureInSharedElements(FragmentTransition.java:924)
    at androidx.fragment.app.FragmentTransition.configureSharedElementsReordered(FragmentTransition.java:634)
    at androidx.fragment.app.FragmentTransition.configureTransitionsReordered(FragmentTransition.java:252)
    at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:152)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2005)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
    at androidx.fragment.app.FragmentManager.run(FragmentManager.java:413)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

是什么原因造成的 NullPointerException 以及如何解决这个问题?!

您应该升级到 Fragment 1.3.5,它修复了这个确切的问题(AppCompat 1.3.0 仅依赖于 Fragment 1.3.4,因此默认情况下您不会有此修复):

implementation "androidx.fragment:fragment:1.3.5"