0

I have a very simple table.

╔════╦═══════╗
║ id ║ title ║
╠════╬═══════╣
║ 1  ║ cow   ║
║ 2  ║ duck  ║
╚════╩═══════╝

ID is INT

TITLE is TEXT

I´m trying to fill an array with these two registers.

collection class has a constructor of (int,String)

My code:

collection[] co=null;

String query="SELECT * FROM collection";
   ps=conn.prepareStatement(query);
   rs=ps.executeQuery();
   int counter=0;
        while(rs.next()) {
            co[counter]=new colleccion(rs.getInt("id"),rs.getString("title"));
            System.out.println(rs.getInt("id"));
            System.out.println(rs.getString("title"));
            counter++;
        }

System.out.println works ok, the values are showed correctly. But it throws an exception as soon as it reaches the array line.

Also tried with column numbers (1 and 2), but it is the same.

Help please.

Martincho
  • 33
  • 8

1 Answers1

1

Here :

collection[] co=null;
[...]
co[counter]=...

You are trying to assign a value to an array that is null.

You must initialize the array before putting values in it : collection[] co= new collection[42]

But as you probably don't know the needed size a priori, you might want to store the items in a List instead.

List<collection> co = new ArrayList<>();
co.add(new collection(rs.getInt("id"),rs.getString("title")));

Note: collection is a terrible name for a class. you shall change it. Class names should begin with an uppercase letter and Collection is already taken (and widely used).

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148