How to Insert null Values in JDate - java

hey guys i m suffering with a problem with NullPointerException i've a jTable wish it have values from those values one Value i put it an Empty value it's a Date this date Can Sometimes Empty means we don't have this Date and Sometimes it's full i tried to Edit this Table so when i click on the Table and click on Button Edit it's shows me a new Frame wish have a Fields to fill them , i want it to populate automaticly it's works very good exept with this empty value wish i've the problem :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
I tried this code
public void fillDateSortie(){
int row = AdminFW.TableStock.getSelectedRow();
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
String dateInString2 = AdminFW.TableStock.getModel().getValueAt(row, 9).toString();
try{
java.util.Date date2 = formatter2.parse(dateInString2);
DateSortieStock.setDate(date2);
}catch(Exception e ){
javax.swing.JOptionPane.showMessageDialog(null, e);
}
if(DateSortieStock.getDate()==null){
DateSortieStock.setDate(null);
}
}

Try with this .This code not will gives you a exception .
if( ((JTextField)DateSortieStock.getDateEditor().getUiComponent()).getText().equals("")){
DateSortieStock.setDate(null);
}
Hope it helps..

Related

Java: Formatting a Date inside of a string

I know I'm probably doing something wrong, but I am trying to format a Date that is currently stored inside of a string but it won't let me parse it to a String because it doesn't recognize it as a Date (because it's in a String variable) and won't let me format it because it cannot format it in its current state. For reference, I am making a time clock application.
I apologize if I'm doing something stupid but I am fairly new to this and have never used SimpleDateFormat before. I put some snippets of code below:
ArrayList<String> punchHistoryTimes = new ArrayList<String>();
SimpleDateFormat sdf =new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public void updatePunchHistory(Sheet sheet){
for(int rowNum:rowNumbers){
punchHistoryTimes.add(sheet.getRow(rowNum).getCell(1).getStringCellValue());
punchHistory.add(new JLabel(sheet.getRow(rowNum).getCell(0).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(1).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(2).getRichStringCellValue().getString()));
}
}
//other code is above this but not relevant to the issue
currentEmployee.setEndTime(sdf.format(currentDate));
if(punchHistory.get(punchHistory.size()-1).getText().contains("Clocked In")){
calcTimeWorked(punchHistory.get(punchHistoryTimes.size()-1).getText(),currentEmployee.getEndTime());
}else{
//This line below is where the error is happening
//value of currentEmployee.getStartTime() at error: 1654653731536
//value of currentEmployee.getEndTime() at error: 07-06-2022 21:02:12
//Both currentEmployee.getStartTime() and currentEmployee.getEndTime() are stored as Strings
calcTimeWorked(currentEmployee.getStartTime(),currentEmployee.getEndTime());
}
currentEmployee.setHoursWorked(differenceInTime);
I tried using the debugger and it shows the error is that it cannot parse 1654653731536. I understand the issue but cannot get a solution. I believe the issue is because when it stores the value in the excel file it is storing the date as a string but then when it pulls the date back out of the excel later (the application would have been closed between these events) it views it as a string and does not recognize that there is a Date inside of the String. Is there any way to cast the String 1654653731536 to a Date?

Date is not being read by JFormattedTextField? Gives `java.lang.NullPointerException`

I am designing a staff data manager which will allow the users to add, edit and view the staff details.
In the code I have a JFormattedTextField defined as follows.
SimpleDateFormat dateDOB = new SimpleDateFormat("dd/MM/yyyy");
JFormattedTextField DOBBX = new JFormattedTextField(dateDOB);
When I want to edit the staff data, I load the date to the JFormattedTextField as follows:
DOBBX.setText(""+retrievedStaff.getDOB());
After editing if I save the data, the value for DOB is null and I get a java.lang.NullPointerException. This only happens if I leave the value for DOB unedited. If I make changes to DOB or enter it again then DOB value is correctly saved.
Also if I add a new staff and then try to edit the staff data without closing the program, the date is properly saved to the binary file with no nullpointer error.
How do I fix this?
(I have no idea how to provide an MCVE for this as my code is quite long and consists of many classes)
Before saving the date to binary file I use the following method to convert it to a string:
public String getDOB() {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try{
String textDate = df.format((DOB));
return textDate;
}catch(Exception e){e.printStackTrace();}
return null;
}
In the StackTrace it is mentioned that the error is produced by this part of the code:
String textDate = df.format((DOB));
I solved this problem. So as I told in the question that the date is properly saved to binary file if I click or change the DOB textbox. So I set the cursor to DOB textfield when the user clicks edit button using requestFocus().

How to set search condition of date, to retrieve other details on that date from database?

These are the basic conditions set in my code.
t1 = new JFormattedTextField(new SimpleDateFormat("dd-MM-yyyy"));
t1.setValue(new java.util.Date());
java.util.Date searchDate=(java.util.Date)t1.getValue();
Retrieving Date from the Result Set.
Date Date1 = rs.getDate("Date1");
I wanted to know whether this condition for matching the dates i enter and for retrieving the dates from database is correct or not. I am new in the world of coding.
if(new java.sql.Date(searchDate.getTime()).equals(Date1))
{
... //code
}
Nevermind...
making it...
java.sql.Date sqlSearchdate = new java.sql.Date(searchDate.getTime());
and
if(sqlSearchdate.equals(Date1)
{
...
}
solved the problem. This was so silly. My bad for asking such a question.
Yes that should work, according to http://www.mkyong.com/java/how-to-compare-dates-in-java/ though i'm not sure why you're creating a new Date object in the if statement.

How to calculate difference between two date from DatePicker widget

I've a problem with my GWT project: i'm only interested to calculate the difference between two date (in days) from two DatePicker Widget.
This is my code, i take it mainly from here: http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/datepicker/client/DatePicker.html
// Create a date picker "FROM: "
final DatePicker datePicker1 = new DatePicker();
datePicker1.addValueChangeHandler(new ValueChangeHandler<Date>() {
public void onValueChange(ValueChangeEvent<Date> event) {
Date date1 = datePicker1.getValue();
}
});
// Set the default value
datePicker1.setValue(new Date(), true);
// Create a date picker "TO: "
final DatePicker datePicker2 = new DatePicker();
datePicker2.addValueChangeHandler(new ValueChangeHandler<Date>() {
public void onValueChange(ValueChangeEvent<Date> event) {
Date date2 = datePicker2.getValue();
}
});
// Set the default value
datePicker2.setValue(new Date(), true);
// =================DEBUG===================
Button send = new Button("send", new ClickHandler(){
public void onClick(ClickEvent event) {
//calculate difference between date1 and date2
days = (int) CalendarUtil.getDaysBetween(date1, date2);
Window.alert("Differece: " + days);
}
});
but while i have no error in eclipse, when i run the web application i have this error:
[ERROR] [progetto] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: Exception caught: null
[...]
I can write more error details if necessary but it's very long...
Can you tell me how to fix this error or how to calculate it with an alternative methods?
Thank you in advance.
it seems to me one of your object is null. look into exception under this exception, there would be more detail. Second tell me where are you calculating days in code and how? if you share more code it would be helpful. But I think you look for date1 and date2 for null. If you can please share more code, i will be more helpful and do the debugging keeping this in mind.

Java method halts when retrieving java.sql.Date object from mysql database, why?

My java class (servlet) has been running fine, but recently, I noticed a problem.
In my database, I have a Date column called 'Full_Expiration_Date'. If one was entered it will store it like '2010-11-17'. If one wasn't entered, is stores it like '0000-00-00'.
In my class, I call the records from the db, and look at the 'Full_Expiration_Date' field to see if it has a date or not. If it does, I execute a few lines of code that check to see if before today's date, and if the date is NOT today's date - if both those conditions are met, the coupon has expired.
So my code works just fine when there IS an expiration date specified, but fails when '0000-00-00' is in the field.
I'm generating an array of information for each coupon in the db table. Once the checking is complete and the array is filled, its sent as a request attribute.
Here's a snippet of my code for this process -
rs = stmt.executeQuery("select Full_Expiration_Date from coupons");
//will hold value from "Full_Expiration_Date" field in db
java.sql.Date expirationDate = null;
//today's date - used for comparison
java.util.Date today = new java.util.Date();
while(rs.next()) {
//get expiration date from db for this record
expirationDate = rs.getDate(12);
if(expirationDate == null) { //should be if the field is 0000-00-00, right?
//don't do any checking against
//expiration date, this record
//doesn't have one
couponList[counter][11] = "";
} else { //10
if(expirationDate.before(today) & !today.equals(expirationDate)) {
couponList[counter][11] = "expired";
} else { //11
couponList[counter][11] = "";
}//if
}//if
counter++;
}//while
Can someone pinpoint what I'm doing wrong here? I'm certain, after testing, that it has to do with the field being 0000-00-00.
0000-00-00 is an invalid date that can't be parsed by Java. You need to allow nulls in that field so that MySQL will stop inserting 0s and that way your if(expirationDate == null) check will actually work.
This is stupid behavior IMO and you should "fix it" by turning on Strict mode. http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_no_zero_date
You can work around this using MySQL's "zeroDateTimeBehavior" configuration property. In your connection properties set:
"zeroDateTimeBehavior" to "convertToNull"
Anytime a 0000-00-00 date is retrieved, it will return null instead of throwing an exception.
Reference: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

Categories

Resources