Android FragmentManager BackStackRecord.run throwing NullPointerException

前端 未结 3 1954
我寻月下人不归
我寻月下人不归 2020-11-27 16:50

I sometimes get the following exception when working with Fragments:

FATAL EXCEPTION: main
java.lang.NullPointerExce         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 17:32

    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.

提交回复
热议问题