I have a fragment (F1) with a public method like this
public void asd() {
if (getActivity() == null) {
Log.d("yes","it is null");
}
}
and yes when I call it (from the Activity), it it is null...
FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();
It must be something that I am doing very wrong, but I don't know what that is
Do as follows. I think it will be helpful to you.
I am using OkHttp and I just faced this issue.
For the first part @thucnguyen was on the right track.
Some HTTP calls were being executed even after the activity had been closed (because it can take a while for an HTTP request to be completed). I then, through the
HttpCallback
tried to update some Fragment fields and got anull
exception when trying togetActivity()
.IMO the solution is to prevent callbacks to occur when the fragment is no longer alive anymore (and that's not just with Okhttp).
The fix: Prevention.
If you have a look at the fragment lifecycle (more info here), you'll notice that there's
onAttach(Context context)
andonDetach()
methods. These get called after the Fragment belongs to an activity and just before stop being so respectively.That means that we can prevent that callback to happen by controlling it in the
onDetach
method.Those who still have the problem with onAttach(Activity activity), Its just changed to 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 -
As suggested by user1868713.
Where do you call this function? If you call it in the constructor of
Fragment
, it will returnnull
.Just call
getActivity()
when the methodonCreateView()
is executed.You can using onAttach or if you do not want to put onAttach everywhere then you can put a method that returns ApplicationContext on the main App class :
After that you can re-use it everywhere in all over your project, like this :
Please let me know if this does not work for you.
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
method to your
Fragment
and putting a break point on it and seeing when it is called relative to your call toasd()
. You'll see that it is called after the method where you make the call toasd()
exits. TheonAttach
call is where theFragment
is attached to its activity and from this pointgetActivity()
will return non-null (nb there is also anonDetach()
call).