I've been working a lot with fragments lately and I was just curious as to what the best practice is for using a reference to a fragment's parent activity. Would it be better to keep calling getActivity() or have a parentActivity variable initialized on the onActivityCreated callback.
3 Answers
This is actually included in the official Android document on Fragments. When you need the context of the parent activity (e.g. Toast, Dialog), you would call getActivity()
. When you need to invoke the callback methods in your Fragment's interface, you should use a callback variable that is instantiated in onAttach(...)
.
public static class FragmentA extends ListFragment {
ExampleFragmentCallbackInterface mListener;
...
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (ExampleFragmentCallbackInterface ) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ExampleFragmentCallbackInterface ");
}
}
...
}

- 15,488
- 5
- 54
- 62
-
Using FragmentCallbackInterface is my preferred way to implement this. – Yen NQ May 21 '15 at 02:17
-
@James: Can you please explain why this approach is better than using getActivity() ? Sometimes getActivity() returns null and the app crashes. By using the above approach, can one be sure that app won't crash ? Thanks. – Rajat Jun 10 '15 at 06:18
-
1If getActivity() is returning null then you haven't been attached yet so `mListener` would also be null. This approach is better than using `getActivity()` because it ensures whatever activity you are attached to implements the interface needed to work with the content in the fragment. – James McCracken Jun 10 '15 at 14:35
-
`onAttach(Activity activity)` is now deprecated in API 23, so this is no longer valid http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity) – CrimsonX Nov 16 '15 at 15:35
getActivity() is best. You need not maintain a variable to store (always, til app cycle!). If needed invoke the method and use! :)

- 942
- 1
- 6
- 18
-
1getActivity() returns null when an activity is recreated.( For example permission changes from settings.) – hkaraoglu Jun 04 '18 at 08:49
If you are in the fragment which is called from some activity, to get the reference to parent activity you can call it inside onViewCreated() or later hook methods of fragment directly by, it is just to make sure that parent activity is not null
getActivity()
If you want to really make sure you need to check first
if (getActivity() != null){ // then your logic with getActivity()}

- 2,342
- 1
- 26
- 33
-
1Can someone explain why this answer is downvoted so much? What is the bad practice here? – dsalaj Apr 13 '19 at 10:12
-