开发者

How to check Null value for Date Object

开发者 https://www.devze.com 2023-04-04 23:07 出处:网络
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 option

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消