Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the Activity from a Fragment

I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment). To this end, I save the activity in an attribute on the fragment when onAttach() is called on the fragment. According to the docs, onAttach() should be called before onCreateView(), which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle() from the Fragment. However, that keeps throwing a NullPointerException. What am I missing here?

like image 447
djc Avatar asked Jun 22 '12 11:06

djc


People also ask

How do you call an activity inside a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

Can fragment access activity variables?

In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity.

How do I access the activity toolbar in fragment?

Though you can add a Toolbar anywhere within your fragment's view hierarchy, you should generally keep it at the top of the screen. To use the Toolbar in your fragment, provide an ID and obtain a reference to it in your fragment, as you would with any other view.

Can a fragment contain an activity?

A fragment represents a modular portion of the user interface within an activity. A fragment has its own lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is running.


1 Answers

You can access the Activity in a Fragment using getActivity(). It can be called safely as soon as onActivityCreated() was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.

If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated was called.

like image 178
Timo Ohr Avatar answered Oct 20 '22 07:10

Timo Ohr