Reputation: 1872
I have created an interface inside a fragment, and implemented it in the parent activity.
When the code looks like this, everything works perfectly:
public class ExercisesCatsFragment extends Fragment {
OnCategorySelected mCallback;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (OnCategorySelected) activity;
}
But when I try to instantiate mCallback in the class itself, I get a nullpointerexception when the interface is called. The non working code looks like this (with no overridden onAttach()):
public class ExercisesCatsFragment extends Fragment {
OnCategorySelected mCallback = (OnCategorySelected) this.getActivity();
Does anyone know the reason behind it? The parent activity is a FragmentActivity; could this be the fault?
Thank you
Upvotes: 0
Views: 2166
Reputation: 48871
In the second (non-working) code you are calling this.getActivity()
in the main body of the Fragment - at that point it isn't attached to an Activity
so this.getActivity()
will return null
.
Just do it the way you show in the first code block or alternatively in the onCreate(...)
method of the Fragment
.
Upvotes: 4