getActivity() returns null in Fragment function

后端 未结 15 1682
别那么骄傲
别那么骄傲 2020-11-22 07:28

I have a fragment (F1) with a public method like this

public void asd() {
    if (getActivity() == null) {
        Log.d(\"yes\",\"it is null\");
    }
}
         


        
15条回答
  •  清酒与你
    2020-11-22 08:11

    This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).

    To avoid this, you can define a field name mActivity and use it instead of getActivity(). This field can be initialized in onAttach() method of Fragment as following:

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    
        if (context instanceof Activity){
            mActivity =(Activity) context;
        }
    }
    

    In my projects, I usually define a base class for all of my Fragments with this feature:

    public abstract class BaseFragment extends Fragment {
    
        protected FragmentActivity mActivity;
    
        @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    
        if (context instanceof Activity){
            mActivity =(Activity) context;
        }
    }
    }
    

    Happy coding,

提交回复
热议问题