Reputation: 145
I am trying to add a CD object into the Band Object's ArrayList member field of an ArrayList of CDs. The band_index is the index of the Band ArrayList when it is selected from a combobox, and i have checked that band_index does assign the correct index of the selected band. I am getting a Null Pointer Exception on this line of code band.get(band_index).addCD(cd);
when i go to call the current Band's addCD method.
Main class:
public void addCD() {
CD cd = new CD(t, y);
band.get(band_index).addCD(cd); //NULL pointer Exception on this line
updateCDs();
}
//Method to print out all the CDs of a band
public void updateCDs() {
String list = "";
for(int i = 0; i < band.size(); i++)
{
//band_index is the index of the selected band in the combobox
if(i == band_index) {
for(int j = 0; j < band.get(i).getCDs().size(); j++) {
list += "Title: " + band.get(i).getCDs().get(j).getTitle();
list += "Year: " + band.get(i).getCDs().get(j).getYear();
}
}
}
System.out.println(list);
}
Band class:
private ArrayList<CD> cds;
public void addCD(CD cd) {
cds.add(cd);
}
CD class:
private String title;
private int year;
public CD(String t, int y) {
title = t;
year = y;
}
public getTitle() { return title; }
public getYear() { return year; }
Upvotes: 0
Views: 338
Reputation: 12523
your cds
is null.
try this:
private List<CD> cds = new ArrayList<CD>();
public void addCD(CD cd) {
cds.add(cd);
}
btw. maybe band is also null. There is not enough source code to determine this.
Upvotes: 6