How to check Null value for Date Object
40,283
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);
}
}
Author by
AngelsandDemons
Updated on September 14, 2020Comments
-
AngelsandDemons over 3 years
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 withDate
object. However this field is optional and hence when user does not select a date the backing bean getter for this particular entry returnsnull
, 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 theif
condition. I want to insertnull
value in DB when user does not select a date. How can I do this? -
Shahzeb over 12 yearsNot only this answer is incorrect but has also got an upvote -unreal.
-
AngelsandDemons over 12 years@Vanathi My problem seems to be solved...I assumed that along with String, Date object can also be checked as null using .equals method and that is why it failed intially...
-
Buhake Sindi over 12 years@Vanathi, your answer is correct but your explanation is wrong.
-
learner over 11 yearsIt worked for me. plz some expert may explain why is this wrong?