28

I am getting a NullPointerException at the modelData.add(i, es) method. I know from debugging that es isn't null. I'm really confused, thanks.

public class EventTableModel extends AbstractTableModel {

    //private int rowCount = 0;
    protected List<EventSeat> modelData;
    private static final int COLUMN_COUNT = 3;
    private Event e;
    Event j = GUIpos.m;
    int i = 1;

public EventTableModel(Event e) {
    this.e = e;
    try {
        System.out.println(modelData);
        for (EventSeat es : e.getEventSeats()) {
            modelData.add(i, es);
            i++;
        }
    } catch (DataException ex) {
        Logger.getLogger(EventTableModel.class.getName()).log(Level.SEVERE, null, ex);
    }

}
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
novicePrgrmr
  • 18,647
  • 31
  • 81
  • 103

4 Answers4

74

You need to initialize a List to not get the NullPointerException.

protected List<EventSeat> modelData = new ArrayList<EventSeat>();
Akshay Talathi
  • 83
  • 1
  • 2
  • 13
Erik
  • 88,732
  • 13
  • 198
  • 189
9

Try

protected List<EventSeat> modelData = new ArrayList<EventSeat>(); 
Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Bonus points if you change this to match the other two answers; I don't think you can instantiate a `List` like that. – phooji Mar 08 '11 at 00:09
6

On the first look, seems like modelData has not been instantiated. I would instantiate the modelData like:

protected List<EventSeat> modelData = new ArrayList<EventSeat>();

FYI.. In Java 7 there will be a new syntax you can use- someObject?.doSomething();

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
  • I don't think e.getEventSeats() returns null (or returns an iterator containing a nulll element). If that were the case the code would terminate at the start of the `for`. – phooji Mar 08 '11 at 00:15
  • Sure..wrote the solution in haste. Thanks for pointing this out. – Piyush Mattoo Mar 08 '11 at 00:19
-1

The modelData was not initialize.Try initialing it using the below snippet.

protected List<EventSeat> modelData=new ArrayList<>();

Thanks

Slycreator
  • 1,144
  • 11
  • 18
  • Welcome to stackoverflow. Your answer doesn't add anything that's not covered by other answers. You can upvote them if you agree with them. See also [answer]. – Robert Jun 29 '21 at 19:49