I have 4 fragments in my app : A
, B
, C
and D
. first of all, one instance of fragment A is added to the activity, without adding to backstack. then the user can dynamically navigate to indefinite number of fragments. suppose this scenario:
addToBackstack addToBackstack addToBackstack addToBackstack
========> A ==============> B ==============> D ==============> D ==============> C
some of these transitions include shared elements as well, for example from B to D:
getActivity().getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.fragment_holder, D.newInstance(bundle), TAG)
.addSharedElement(view, name)
.addToBackStack(null)
.commit();
now I need to take user from last fragment directly to the first fragment (A). so I have tried:
getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
which works well, but not always. sometimes (I have not been able to find the exact scenarios which definitely result in exception) it crashes the app with the following logs:
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$4.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)
what is causing this NullPointerException
and how to solve the issue?!
You should upgrade to Fragment 1.3.5, which fixes this exact issue (AppCompat 1.3.0 depends only on Fragment 1.3.4, so you wouldn't have this fix by default):
implementation "androidx.fragment:fragment:1.3.5"