Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context in a PreferenceFragment

taken from http://developer.android.com/guide/topics/ui/settings.html:

Note: A PreferenceFragment doesn't have a its own Context object. If you need a Context object, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.

If I call getActivity() from within the OnCreate() method of a PreferenceFragment then can I be assured that the fragment is attached to its activity - or is there some other way you should get the Context in this instance?

The reason I need a Context is I'm trying to use a Toast notification from the PreferenceFragment

like image 732
bph Avatar asked Aug 31 '12 09:08

bph


1 Answers

If you want to make sure that a Context is available you'll need to wait until the Fragment has been attached to an Activity. The callback for this is the onAttach(Activity) method.

Depending on the lifecycle state of your fragment the getActivity() method can also return null.

like image 102
keyboardsurfer Avatar answered Nov 09 '22 04:11

keyboardsurfer