Android FragmentManager BackStackRecord.run throwing NullPointerException

别说谁变了你拦得住时间么 提交于 2019-11-26 20:18:54

Answering my own question:

This exception is (eventually) thrown when you call FragmentTransaction.remove(null); and FragmentTransaction.commit();

EDIT: And also, like Twice Circled and shinyuX point out in the comment; when calling the show(null) or add(null), attach(null) and detach(null) methods, and probably also hide(null)

After calling commit(), the transaction will be queued in the FragmentManager. As a result, when the operation is being processed after you explicitly call FragmentManager.executePendingTransactions(), or when the FragmentManager queue thread calls it, it throws a NullPointerException.

In my case, I was maintaining fragment states in a global object. There I checked if the fragment was showing or not, and then removed visible fragments. But because I started a new FragmentActivity, these states were still set to true while they were not visible. So this is a design error.

Other than fixing the design error, the solution was simple: check whether FragmentManager.findFragmentByTag() returned null before removing the fragment.

The one reason why it happens it is invoking

getSupportFragmentManager().beginTransaction().remove(fragment)

while fragment is null

I don't use tag to create the fragments (they works like TabBar containers).

So, it works when change Tab, but if I press back button I got the same error.

At onDestroyView method I found fragment instance with FragmentManager#findFragmentById, however FragmentManager#findFragmentByTag returns null, sure.

class MyFragment extends ListFragment {

@Override
public void onDestroyView() {
    super.onDestroyView();

    if (this.mapFragment != null
            && getFragmentManager().findFragmentById(
                    this.mapFragment.getId()) != null) {

        getFragmentManager().beginTransaction().remove(this.mapFragment)
                .commit();
        this.mapFragment = null;
    }

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