Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

List of Custom Classes

I'm trying to put what I've learnt into real examples.

The declaration:

    protected List<ColourBoxes> mBoxes;

The snippet of the code is:

if(i == correctNumber){
                ColourBoxes correctBox = new ColourBoxes(levelColour()+3);
                mBoxes.add(correctBox);
            }

and the colourboxes class is:

public class ColourBoxes {
    int mColour;

    public ColourBoxes(int colour) {
        this.mColour = colour;
    }

}

However, when I tried to run it, it keeps erroring out on the mBoxes.add line because as it's returning a null pointer.

anyone can explain to me why this is the case?

Cheers :)

1 Answer

Simple fix. You generally get a null pointer error when you don't initialise a object. Do the following:

// Replace this
protected List<ColourBoxes> mBoxes;

// With this
protected List<ColourBoxes> mBoxes = new ArrayList<ColourBoxes>();

Let me know if that helps!

That has worked, thanks very much Ratik!