LoneDuck
LoneDuck

Reputation: 1872

Android- interface in fragment will instantiate in onAttach() but not otherwise

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

Answers (1)

Squonk
Squonk

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

Related Questions