I have a fragment (F1) with a public method like this
public void asd() {
if (getActivity() == null) {
Log.d(\"yes\",\"it is null\");
}
}
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).
Those who still have the problem with onAttach(Activity activity), Its just changed to Context -
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity a; //Your activity class - will probably be a global var.
if (context instanceof mActivity){
a=(mActivity) context;
}
}
As suggested by user1868713.
Where do you call this function? If you call it in the constructor of Fragment
, it will return null
.
Just call getActivity()
when the method onCreateView()
is executed.