Very simple error I’m sure, just having a mental block for some reason!
I have an object which contains an ArrayList of other objects. When I try to initialise the list in the constructor it does not seem to initialise and I get a nullpointer when I attempt to access the list within the code.
Order class variables:
private int covers;
private int table;
private ArrayList<MenuItem> items;
Here is the Order class:
public Order(int covers, int table) {
super();
this.covers = covers;
this.table = table;
this.items = new ArrayList<MenuItem>();
}
Here is the code within the MainActivity causing me problems:
order = new Order();
order.setCovers(2);
order.setTable(1);
order.addToOrder(new MenuItem("Item 1", 12.99));
Toast.makeText(getApplicationContext(), "order size: " + order.getItems().size(), Toast.LENGTH_SHORT).show();
I would expect the Toast to display “1”. However when I ran debugger I noticed the order object ArrayList attribute was equal to null.
Any idea why? Thanks in advance!
EDIT: addToOrder method:
public void addToOrder(MenuItem m){
items.add(m);
}
You have failed to initialize
items. Useinstead of
itemsis initialized insidenot on the default constructor.