Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActivity() returns null in Fragment function

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 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.

like image 948
Lukap Avatar asked Jun 02 '11 13:06

Lukap


1 Answers

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).

like image 137
PJL Avatar answered Sep 28 '22 23:09

PJL