JavaNullPointer
JavaNullPointer

Reputation: 1211

Adding a Object in a Objectlist (ArrayList)!

i have three classes. 1.Class:`

public class Handler {

private String name;
private String short_name;
private int semester; 
private int modul_number; 

private String prof; 
private int credits; 
private double note; 
private ArrayList<Handler_date> dates;



public Handler() {

}

public Handler(String _name, String _short_name, int _semester, int _modul_number,
         String _prof, int _credits, double _mark) {
    this.modul_number=_modul_number;
    this.name = _name;
    this.short_name = _short_name;
    this.semester = _semester;
    this.prof = _prof;
    this.credits = _credits;
    this.note= _mark;
    dates = new ArrayList<Handler_date>();

}

public void add_date(String _room, int _time, 
        String _day) {
    Handler_date temp = new Handler_date(_room, _time, 
            _day);
    dates.add(temp);
}`

and the 2.class (Elementclass):

`public class Handler_date {

private String room; 
private int time; 
private String day; 

public Handler_date() {
}

public Handler_date(String _room, int _time, 
        String _day) {
    this.room = _room;
    this.time = _time;
    this.day = _day;
}

}

I want to add a modul, but i get a NullPointerException for dates.add(temp);

i call the method with templist.search_modul_number(modulnumber).add_date("room", 1, "monday");

My Handler-Objects are saved in a extra Objectlist/class to an arrayList ...private ArrayList<Handler> handlerlist; Anyone an idea what I am doing wrong?

Thanks!

Upvotes: 1

Views: 249

Answers (3)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

Your dates field is not initialized. Probably because you created Handler instance using no-arg constructor.

Upvotes: 0

Peter Svensson
Peter Svensson

Reputation: 6173

Most likely you're not initializing private ArrayList<Handler_date> dates;.

You have a no-args constructor for Handler which doesn't create a list.

Change it to:

public Handler() {
    dates = new ArrayList<Handler_date>();
}

Upvotes: 2

burna
burna

Reputation: 2962

Your dates arraylist is not initialized. It is null, so you get this exception.

Are you calling new Handler(); - in that constructor, you don't init dates.

And in the future, please attach the full stacktrace to get help.

Upvotes: 1

Related Questions