androidandroid-fragmentsfragmentmanager

getHandler() NullPointerException when calling popBackstackImmediate() on a FragmentManager


I have this sime line in my code:

getChildFragmentManager().popBackstackImmediate();

It sometimes works, but often crashes. Here's the stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Handler android.support.v4.app.FragmentHostCallback.getHandler()' on a null object reference
          at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1646)
          at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:585)
          at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:600)
          at marg.uk.fourthoffice.fragments.BCMasterDetailFragment.popBackStack(MyMasterDetailFragment.java:140)
          at marg.uk.fourthoffice.activities.BCOfficeActivity.onBackPressed(MainActivity.java:173)
          at marg.uk.fourthoffice.fragments.BCSwipeableCardsFragment$1.onClick(MyOtherFragment.java:189)

Any idea where could be an issue?


Solution

  • It turned out that there was an error in my code.

    I can't show an example because there were a bunch of issues with my Activity-Fragment architecture, but the main issue was that getChildFragmentManager was actually empty and it was being called from the wrong fragment.

    This was happening on a tablet (dual pane layout) where there were 4+ fragments being alive at the same time. This was being called on the wrong fragment.

    So if you are experiencing a similar issue, you might have multiple instances of the same fragment in memory. Make sure that you are calling this method from the correct instance.