You can use the getActivity() method to get context or You can use getContext() method .
onCreate is called on initial creation of the fragment. You do your non graphical initializations here. It finishes even before the layout is inflated and the fragment is visible. onCreateView is called to inflate the layout of the fragment i.e graphical initialization usually takes place here.
This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.
You can use getActivity()
, which returns the activity associated with a fragment
.
The activity is a context
(since Activity
extends Context
).
To do as the answer above, you can override the onAttach
method of fragment:
public static class DummySectionFragment extends Fragment{
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
DBHelper = new DatabaseHelper(activity);
}
}
The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup
when you call onCreateView
method at least here you are sure not to get null for getActivity()
:
public class Animal extends Fragment {
Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.getContext();
Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity
returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With