• Post Reply Bookmark Topic Watch Topic
  • New Topic

class problem when a null value is found.  RSS feed

 
Dave Bosky
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class that reads a few records in from a database. Some of the fields are optional and may contain a null value. Whenever my class is reading the rows and encounters a null value in a field(ItemSize) it blows up with an error HTTP Status 500.
org.apache.jasper.JasperException: Exception in Catalog ProductModel/getProductsnull
This is the line it that errors out.
------------------
product.setItemSize(rslt.getString("ItemSize").trim());
------------------
-------------
public class ProductModel implements Serializable {
private static Connection conn;
public ProductModel (Connection c) {
this.conn = c;
}
public static Collection getProducts() {
ArrayList productList = new ArrayList();
CallableStatement cstmt;
try {
cstmt = conn.prepareCall("{call dbo.usp_products()}");
ResultSet rslt = cstmt.executeQuery();
while(rslt.next()) {
ProductBean product = new ProductBean();
product.setItemID(rslt.getInt("ItemID"));
product.setItemSize(rslt.getString("ItemSize").trim());
product.setName(rslt.getString("Name").trim());
productList.add(product);
}
rslt.close();
cstmt.close();
return productList;
}
catch(Exception ex) {
throw new RuntimeException("Exception in ProductModel/getProducts" + ex.getMessage());
}
}
public void close() {
this.conn = null;
}
}
There has to be a simple answer If all my fields contain a non-null value the class works like a dream!
Thanks,
Dave
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, it's simple. Your expression rslt.getString("ItemSize") returns null. Then you try to run the method trim() on it, and you can't run a method on nothing. So you have to take a couple steps instead of one lovely one.

You will rapidly grow tired of typing this for field after field, and may move that logic into a generic method so you can say something like:

Note that I took a leap and not only moved this logic into its own method, but moved it to a static method on a utility class so I can use it for years to come.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

To answer this, you have to ask yourself what happend if rslt.getString("ItemSize") returns null. Then you have:

which is, of course, going to throw a null-pointer exception.
Try breaking the line into two parts; only trim if the value is not null
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!