简体   繁体   中英

How to check Null value for Date Object

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?

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);

    }
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM