Organiccat
Organiccat

Reputation: 5651

Generics and Collections in GWT, Null Pointer

When calling a method that adds an object to a collection in GWT I get a null pointer error. I have no idea why as everything I have done creates a very simple object (only contains a string). Here is the code that calls the function and the function:

public class PlantMenu extends VerticalPanel {

    private Collection<PlantData> plantList;
    private Collection<PlantData> newPlantData;

    public PlantMenu() {
        createPlants();
        /*
        for(Iterator<PlantData> i = plantList.iterator(); i.hasNext();) {
            Window.alert(i.next().getPlantName());
        }*/
    }

    public Collection<PlantData> createPlants() {
        PlantData plant1 = new PlantData("Herbs");
        PlantData plant2 = new PlantData("Flowers");
        PlantData plant3 = new PlantData("Vegetable");

        newPlantData.add(plant1);
        newPlantData.add(plant2);
        newPlantData.add(plant3);
        return newPlantData;
    }

}

It errors out (null pointer) when trying to add the first plant, this line:

PlantData plant1 = new PlantData("Herbs");

Any help appreciated :)

Upvotes: 1

Views: 3575

Answers (2)

rustyshelf
rustyshelf

Reputation: 45111

You have not initialised your variables properly, this has nothing to do with GWT and is just basic Java. Here's a working version:

public class PlantMenu extends VerticalPanel {

    private List<PlantData> plantList = new ArrayList<PlantData>();
    private List<PlantData> newPlantData = new ArrayList<PlantData>();

    public PlantMenu() {
        createPlants();
        for(PlantData plant : newPlantData) {
                Window.alert(plant.getPlantName());
        }
    }

    public List<PlantData> createPlants() {
        newPlantData.add(new PlantData("Herbs"));
        newPlantData.add(new PlantData("Flowers"));
        newPlantData.add(new PlantData("Vegetable"));
        return newPlantData;
    }

}

As a side note, you shouldn't be extending VerticalPanel, but rather extending Composite and then using a vertical panel as your widget using setWidget(...);

Upvotes: 0

Adeel Ansari
Adeel Ansari

Reputation: 39907

You didn't initialize your collections. Despite, you already told that its not on that line, but I doubt it. Showing a full exception stack would be much more helpful though. And the exception may occur in your PlantData constructor, but you didn't show it here.

You could do something like this,

private Collection<PlantData> plantList = new ArrayList<PlantData>();
private Collection<PlantData> newPlantData = new ArrayList<PlantData>();

I have used ArrayList, because generally we use ArrayList. Other implementation can also be used, according to the requirements.

Upvotes: 5

Related Questions