I have a fragment (F1) with a public method like this
public void asd() {
if (getActivity() == null) {
Log.d(\"yes\",\"it is null\");
}
}
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,