Ali
Ali

Reputation: 187

NullPointerException on Fragment Array

The declaration of the array.

public ExerciseFragment[] fragments;

The initialization.

fragments = new ExerciseFragment[numberOfWorkouts];

And finally, setting each fragment equal to it's respective ExerciseFragment.

for (int i = 0; i < numberOfWorkouts; i++) {
        ft.add(LinearLayoutID, new ExerciseFragment(), "KEY"+i);
        fragments[i] = (ExerciseFragment) getFragmentManager().findFragmentByTag("KEY"+i);
    }

whyn trying to access fragments[] I always get a NullPointerException and I have searched and searched with no luck, I can't find where I went wrong, hopefully some fresh eyes can!

Upvotes: 0

Views: 452

Answers (1)

Jevan
Jevan

Reputation: 131

What about changing it to:

for (int i = 0; i < numberOfWorkouts; i++) {
    fragments[i] = new ExerciseFragment();
    ft.add(LinearLayoutID, fragments[i], "KEY"+i);
}

Does that still give an error message when you run that?

I'm thinking that getFragmentManager() might be returning null in your question. Since I can't see the code for getFragmentManager, declaration and assignment for ft, and findFragmentByTag, so I can't be sure.

Upvotes: 1

Related Questions