Reputation: 33
I am basically trying to retrieve to an ArrayList
something i stored in my database. I iterate through ResultSet but it I get a NullPointerException
.
ResultSet rs = null;
ArrayList<People> peoList=null;
try {
rs = stat.executeQuery("SELECT * from people WHERE surname='"+surname+"'");
}
catch (SQLException ex) {
Logger.getLogger(myClass.class.getName()).log(Level.SEVERE, null, ex);
}
String name, surname;
try {
while (rs.next()) {
name = rs.getString("name");
surname = rs.getString("surname");
People peo = new People(name,surname);
peoList.add(peo);
}
}
catch (SQLException ex) {
Logger.getLogger(myClass.class.getName()).log(Level.SEVERE, null, ex);
}
return peoList;
When I call this function, a NullPinterException
arises with a ton of other messages. I really don't get this. It seems that the problem is where I put peoList.add(peo);
. For example, if remove this and put a counter the number of iterations is ok.
Upvotes: 2
Views: 109
Reputation: 14381
while(rs.next())
{
name = records.getString("name");
surname = records.getString("surname");
People peo= new People(name,surname);
peoList.add(peo);
}
Where did records
come from? This is not the variable name for your ResultSet
, instead you named it rs
.
I think you mean to do:
while(rs.next())
{
name = rs.getString("name");
surname = rs.getString("surname");
People peo= new People(name,surname);
peoList.add(peo);
}
The exception is being thrown in your original code because name
and surname
are both null, as is records
because it does not exist.
UPDATE:
As a comment mentioned, you appear to also not have initialized peoList
.
You're code is a little difficult on the eyes, due to mixed style, etc.
I re-wrote some of it, but here's the gist (including a properly initialized peoList
:
final static Logger LOG = Logger.getLogger(myClass.class.getName());
ResultSet rs = null;
try {
rs = stat.executeQuery("SELECT * from people WHERE surname='"+surname+"'");
} catch (SQLException ex) {
LOG.severe("", ex);
}
String name, surname;
List<People> peoList = new ArrayList<People>();
try {
while(rs.next()) {
name = rs.getString("name");
surname = rs.getString("surname");
People peo= new People(name,surname);
peoList.add(peo);
}
} catch (SQLException ex) {
LOG.severe("", ex);
}
return peoList;
Upvotes: 1