getActivity() returns null in Fragment function
Solution 1:
commit
schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.
I'd suggest adding an
onAttach(Activity activity)
method to your Fragment
and putting a break point on it and seeing when it is called relative to your call to asd()
. You'll see that it is called after the method where you make the call to asd()
exits. The onAttach
call is where the Fragment
is attached to its activity and from this point getActivity()
will return non-null (nb there is also an onDetach()
call).
Solution 2:
The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.
@Override
public void onAttach(Context context) {
super.onAttach(activity);
mContext = context;
}
@Override
public void onDetach() {
super.onDetach();
mContext = null;
}
Solution 3:
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,