How do i handle an empty jXDatePicker? - java

I have a swing form which includes jXDatePicker to capture dates. When a date is not selected in the jXDatePicker an error is thrown when the trying to inserting the date into the database. Below is the error I am getting in Netbeans:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
Below is the code that is giving me errors:
String dateOpened, dateOfLastUpdate, dateOf1stDelinquency, dateOfLastPayment, dateClosed;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOpened = format.format(jXDatePicker7.getDate());
dateOfLastUpdate = format.format(jXDatePicker2.getDate());
dateOf1stDelinquency = format.format(jXDatePicker4.getDate());
dateOfLastPayment = format.format(jXDatePicker5.getDate());
dateClosed = format.format(jXDatePicker6.getDate());
String query2 = "insert into ACCOUNT (ACCOUNT_NUMBER,DATE_CLOSED ,DELINQUENCY_DATE, UPDATE_DATE,AMOUNT_OWING,"
+ "BALANCE,PAYMENT_HISTORY,ACCOUNT_STATUS,MONTHLY_PAYMENT,TERMS_DURATION,PRINCIPAL,CREDIT_LIMIT,"
+ "DATE_OPENED,PORTIFOLIO_TYPE,ACCOUNT_TYPE,NATIONAL_ID,COSIGNER_NATIONAL_ID)"
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement2 = con.prepareStatement(query2);
preparedStatement2.setString(1, acc_no);
preparedStatement2.setString(2, dateClosed);
preparedStatement2.setString(3, dateOf1stDelinquency);
preparedStatement2.setString(4, dateOfLastUpdate);
preparedStatement2.setDouble(5, amount_owing);
preparedStatement2.setDouble(6, current_balance);
preparedStatement2.setString(7, payment_history);
preparedStatement2.setString(8, account_status);
preparedStatement2.setDouble(9, monthly_payment);
preparedStatement2.setDouble(10, terms_duration);
preparedStatement2.setDouble(11, principal);
preparedStatement2.setDouble(12, credit_limit);
preparedStatement2.setString(13, dateOpened);
preparedStatement2.setString(14, portfolio_type);
preparedStatement2.setString(15, acc_type);
preparedStatement2.setString(16, national_id);
preparedStatement2.setString(17, cosigner_national_id);
preparedStatement2.executeUpdate();
Some dates are not required and applicable on some instances, therefore the user cannot select a date under such circumstances.

Check each individual JXDatePicker's date like jXDatePicker2.getDate() for null. Do not call format.format if that date does happen to be null. I get that exact same error you mentioned on the format.format line if the date is empty and enter is pushed. Instead, go for some default time, like new Date(0); meaning:
format.format(new Date(0));

Use following code and make sure that dateOpened column in database accept NULL values.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
dateOpened = null;
}
If you don't want to insert NULL value then show error message as
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
//error
}

Related

How to solve this error "String Cannot be converted to Date"?

Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.

XPath Filter by Date

I need to filter the records by date through JAVA class:
public static final String DATE_TIME = "DateTime"
Date dateNow = setTimeToZero(Calendar.getInstance().getTime());
String date = DATE_TIME_FORMAT.format(dateNow);
Request request = table.createRequest();
DATE_FILTER = XPathFilter.newFilter("date-greater-than(" + Root_Table_DateField.format() + '$date')");
request.setXPathFilter(DATE_FILTER);
request.setXPathParameter(DATE_TIME, date);
RequestResult = reqResult = request.execute();
The field I am trying to access is define as DateTime, but I don't want the time now, so I set the time to zero, so I can filter for all field with date greater than dd-MM-yyyT00:00:00:000
But it return a predicate error: PredicateException: Invalid XPath expresion ./dateTime = 26-06-2020T00:00:00:000 - Unexpected 'T00:00:00.000'
Any clue?
Thank you
Try to add the date formatted like that (xs:date("2020-06-26Z")
date-greater-than(xs:date("2004-12-25-12:00"), (xs:date("2020-06-26Z"))
Reference: https://www.w3.org/TR/xpath-functions-31/

If statement on the server side using iText results in Connection failed

I am using GWT, java, iText to produce a PDF and want to reformat the date. However, this code, on the server side, results in the message "Connection failed" on the client side (there are no error messages in the log) and no output:
String storedName = " ";
DateTimeFormat sdf = DateTimeFormat.getFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = sdf.parse(scoutNamesDescription.getAwardedDate());
String awardedString = DateTimeFormat.getFormat("dd-MM-yyyy").format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
When I comment out the date reformatting this works.
I have tried replacing the reformatting with:
System.out.println(scoutNamesDescription.getAwardedDate());
formatedDate = StringUtils.substring(scoutNamesDescription.getAwardedDate(), 8, 2) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 4, 4) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 0, 2);
System.out.println(formatedDate);
And this also produces the same error between the two println.
Based on Andrei Volgin's reply I have the following:
String storedName = null;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = df1.parse(scoutNamesDescription.getAwardedDate());
String awardedString = df2.format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
}
You cannot use GWT code on the server side. And in this case there is no need.
Use standard Java tools for formatting dates:
Convert java.util.Date to String

Converting items inside ArrayList to different types

I have a part inside my program where the user logs into have access to the application, when the user logs in I have a time stamp being taken and stored into an ArrayList. When the user logs out I have another time stamp taken for when they logged out. I have been trying to subtract the 2 times from each other, but it is not allowing me to. They are stored in a String ArrayList, I am aware you can't subtract String, so I have tried converting to double, int, date, etc... None of it works for me. My question is that I would like the difference between the two times. I am also aware that there are other question similar to this on SO, but none specific to this exact question, that is why I posted it. I am not trying to post a duplicate.
Code:
loginButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'loginButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//gets texts from specified text fields and assigns to instance variable
String userNameFromLogin = userNameTextBox.getText().trim();
String password = passwordTextBox.getText().trim();
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String loginTime = dateFormat.format(date);
//sql statement that check if username and password exist
String sql5 = "SELECT User_name,Password FROM Employee_Table WHERE User_name = '" + userNameFromLogin + "' and Password = '" + password + "'";
//execute query, assigning all records in db to 'rs5'
rs5 = st.executeQuery(sql5);
//instance variables
int count = 0;
//loops until reaches end up 'rs5'
while(rs5.next())
{
count++;
}
//statement and actions if 'userName' and 'password' match
if(count == 1)
{
//sets 'welcomeFrame' to true
welcomeFrame.setVisible(true);
//sets 'loginFrame' to false
loginFrame.setVisible(false);
//sets text fields to blank
userNameTextBox.setText("");
passwordTextBox.setText("");
//adds 'userNameFromLogin' to array
loginArray.add(userNameFromLogin);
//adds 'loginTime' to array
loginArray.add(loginTime);
//sets label to current username logged in
userNameLabel.setText("logged in as: " + userNameFromLogin);
}
//statement and actions if 'userName' and 'password' do not match
else
{
JOptionPane.showMessageDialog(null, "Username or password incorrect!");
userNameTextBox.setText("");
passwordTextBox.setText("");
}
}
catch(Exception ex)
{
}
}
});
}
logoutHomeButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'employeeFormButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String logoutTime = dateFormat.format(date);
//sets 'loginFrame' to visible
loginFrame.setVisible(true);
//sets 'welcomeFrame' to not visible
welcomeFrame.setVisible(false);
//adds 'logoutTime' to array
loginArray.add(logoutTime);
//statement that selects everything from our 'Login_Info'
String sql7 = "SELECT * FROM Login_Info";
//execute query, assigning all records in db to 'rs7'
rs7 = st.executeQuery(sql7);
//moves cursor to next row
rs7.moveToInsertRow();
//inserts record into db
rs7.updateString("User_Name", loginArray.get(0));
rs7.updateString("Login_Time", loginArray.get(1));
rs7.updateString("Logout_Time", loginArray.get(2));
//inserts data into db
rs7.insertRow();
JOptionPane.showMessageDialog(null, "You have successfully logged out!");
}
catch(Exception ex)
{
}
}
});
}
The ArrayList is a global variable at the top of my program. The two variable names I will be subtracting are loginTime and logoutTime and their respected indexes inside the ArrayList.
Thanks for any guidance
You can convert the strings back to dates using your SimpleDateFormat.parse(). Once they are both in Date format:
long elapsed = logoutDate.getTime() - loginDate.getTime(); // Elapsed time in ms

cannot convert java.util.Date to java.sql.Date with JXDatePicker

i am using a JXDatepicker here. i dont know what to do with the error please help me. i tried a lot but failed.
i tried to print what cause this error and it prints this message. i want the format to be yyyy/MM/dd cause i want it to insert into the database.
AddProductGUI.java
txtExpiration = new JXDatePicker(); txtExpiration.setName("Expiration");
txtExpiration.setBorder(null);
txtExpiration.setFormats(new SimpleDateFormat("yyyy.MM.dd"));
AddProduct.java
public java.util.Date returnDate(JXDatePicker txtExpiration, Boolean isExpiring) {
if (isExpiring) {
return txtExpiration.getDate();
} else {
return null;
}
}
ActionToDatabase.java
if (!DatabaseValidator
.isExistingData(
"select ProductID from tblIndividualProduct where ProductID =?",
product.getProductID())) {
sql = "insert into tblIndividualProduct (ProductId,Code,Expiration,Note,UpdatedPrice,PriceChanged) Values(?,?,?,?,?,?)";
connection
.setPreparedStatement((PreparedStatement) connection
.getConnection().prepareStatement(sql));
connection.getPreparedStatement().setString(1,
product.getProductID());
connection.getPreparedStatement().setString(2,
product.getCode());
//connection.getPreparedStatement().setDate(3, new java.sql.Date(product.getExpiration().getTime()));
**connection.getPreparedStatement().setDate(3, (java.sql.Date)product.getExpiration());**
connection.getPreparedStatement().setString(4,
product.getNote());
connection.getPreparedStatement().setDouble(5,
product.getPrice());
connection.getPreparedStatement().setBoolean(6,
product.getPriceChanged());
connection.getPreparedStatement().executeUpdate();
System.out
.println("Successfully added individual product ("
+ product.getProductID()
+ ") to the database");
Create a new instance of a java.sql.Date using the java.util.Date as the base value, for example
connection.getPreparedStatement().setDate(3,
(product.getExpiration() == null ?
null :
new java.sql.Date(product.getExpiration().getTime())));
It would be possible to pass a java.sql.Date to JXDatePicker as java.sql.Date extends from java.util.Date, but it won't work the other way around (you can't cast a java.util.Date to a java.sql.Date without first knowing that the object is acutally a java.sql.Date masquerading as a java.util.Date

Categories

Resources