0

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; }
5
  • 1
    What does band.get(band_index) do ? Initialize private ArrayList<CD> cds = new ArrayList<>(); Commented May 28, 2013 at 11:25
  • Where are you initializing band? Commented May 28, 2013 at 11:26
  • thank you. i forgot about it Commented May 28, 2013 at 11:28
  • Use a StringBuilder in updateCDs() and looking at its code I don't understand why you don't call it printCDs() or something? Commented May 28, 2013 at 11:29
  • The general approach is: fire up a debugger, and figure out which subexpression is null first. Commented May 28, 2013 at 11:30

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

doh that was a simple mistake. i forgot to initialize the cds... thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.