I am getting null pointer exception again and again while getting value from database table.....why its giving me null pointer exception?
Here is my code :
private HashSet getPlayerList() {
HashSet hs = new HashSet();
String soccername = "";
try {
conn = ConnectionProvider.getConnection();
rs = null;
pstmt = null;
String sql = "Select * from Players where deleted = false";
if (conn != null) {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
soccername = rs.getString("soccername").trim();// this line giving exception
if (soccername == null || soccername.isEmpty()) {
soccername = rs.getString("name").trim();
}
hs.add(soccername);
}
}
} catch (NamingException ex) {
System.out.println(ex);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
pstmt.close();
rs.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
return hs;
}
that is wrong:
soccername = rs.getString("soccername").trim();// this line giving exception
if (soccername == null || soccername.isEmpty()) {
if rs.getString("soccername")
returns null it must leads to a NPE because it is followed by the function trim()
.
better is:
soccername = rs.getString("soccername");
if (soccername == null || soccername.trim().isEmpty()) {
It should be:
soccername = rs.getString("soccername");
if (soccername == null || soccername.isEmpty()) {
soccername = rs.getString("name").trim();
} else {
//now you are sure that soccername is not null
soccername = soccername.trim();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.