4

I am using JSF 2.0 and RichFaces 3.3. In my View user will pich a date from a calendar. Tag used is <rich:calendar>. This is mapped in backing bean with Date object. However this field is optional and hence when user does not select a date the backing bean getter for this particular entry returns null, which is right.

My problem is that I have to store this date in DB. So before storing I am type casting it in this manner:

if (newProfile.get(Constants.DETAILS_EXPIRY_DATE_1).equals(null)) {
    this.cStmt.setDate(15,null);
} else {
    java.sql.Date sqlDate = new java.sql.Date(((java.util.Date)newProfile.get(Constants.DETAILS_EXPIRY_DATE_1)).getTime());
    this.cStmt.setDate(15,sqlDate);
}

However it is throwing a NullPointerException in the if condition. I want to insert null value in DB when user does not select a date. How can I do this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AngelsandDemons
  • 2,823
  • 13
  • 47
  • 70
  • Post the stack trace. By the look of it if you are getting nullpoint at if it can only be from 'newProfile' meaning it is not initialized nothing to do with do. – Shahzeb Sep 13 '11 at 05:17
  • 1
    @Shahzeb, it might also be that the `newProfile.get(Constants.DETAILS_EXPIRY_DATE_1)` returns a `null`. – Buhake Sindi Sep 13 '11 at 05:20
  • true @The. Ankit post stacktrace also show some more code . – Shahzeb Sep 13 '11 at 05:25
  • Yeah...that line is returning null but that is why I want to check for null value....I know when won't select a date it will have null value..and since it contains null value I will store null value without type casting..But if condition itself is throwing Null Pointer Exception,. – AngelsandDemons Sep 13 '11 at 05:28

2 Answers2

5

If you want to be more robust in avoiding NullPointerException,

if (newProfile != null) {
    Object obj = newProfile.get(Constants.DETAILS_EXPIRY_DATE_1);
    if (obj == null) {
        this.cStmt.setDate(15, null);
    } else {
        java.sql.Date sqlDate = new java.sql.Date(((java.util.Date)obj).getTime());
                this.cStmt.setDate(15,sqlDate);

    }
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
-2

Try if(newProfile.get(Constants.DETAILS_EXPIRY_DATE_1) == null)

For String, you can use equals() method. Also, objects need null check before using equals method to avoid NullPointerException.

Vaandu
  • 4,857
  • 12
  • 49
  • 75