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

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

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.

(H2O.ai) How to handle empty timestamp values in hex.genmodel.easy.EasyPredictModelWrapper.predictBinomial

Using h2o, I have used a .csv data frame that includes a column of dates, some of which are NULL, to train a model. Looking at the .hex dataframe that was output by h2o Flow UI after parsing the input .csv file, the null values are represented by .s and the remaining dates are represented as timestamp doubles (ie. milliseconds since epoch time).
When trying to use the model's MOJO file in a java program to make predictions, on a dataset, I am getting the error
Exception in thread "main" java.lang.NullPointerException
at hex.genmodel.easy.EasyPredictModelWrapper.fillRawData(EasyPredictModelWrapper.java:554)
at hex.genmodel.easy.EasyPredictModelWrapper.predict(EasyPredictModelWrapper.java:615)
at hex.genmodel.easy.EasyPredictModelWrapper.preamble(EasyPredictModelWrapper.java:489)
at hex.genmodel.easy.EasyPredictModelWrapper.predictBinomial(EasyPredictModelWrapper.java:303)
at SimpleCsvPredictor.predictCsv(SimpleCsvPredictor.java:287)
at SimpleCsvPredictor.main(SimpleCsvPredictor.java:210)
since I am handling NULL values in the dataset's date column by setting them t null in the RowData object that h2o's model EasyPredictionModelWrapper can make predictions on.
The problem is that, for this column, the model is expecting a Double value. But there is no Double value to pass in because the value is null. Note that I cannot just set these null values to 0.0 because of how the model is trained (since not all the dates are null, so setting some to zero would be misrepresenting the particular sample the the model). So how can I fix this or what can I put in the place of a null where a Double is expected?
Thanks for the advice :)
Here is what I do to the date Strings before I row.put("date_field", "<date string>") some <date string> into a RowData object (see here) that EasyPredictModelWrapper can predict on:
/**
*
* #param str_date (in MM/dd/yyyy form)
* #return string representation of timestamp value, either the string value of the str_date timestamp or "NULL"
* if can parse str_date to Date object, else returns null
*/
private String dateString2TimestampString(String str_date) {
if (str_date.toUpperCase().equals("NULL")) {
return "NULL";
} else {
try {
// convert date (MM/DD/YYYY) string to java date
DateFormat formatter;
formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = (Date) formatter.parse(str_date);
// convert date string to timestamp (since epoch time) (double??)
double epochTimestamp = (double) date.getTime();
return new BigDecimal(epochTimestamp).toPlainString();
} catch (Exception e) {
System.out.println("** dateString2TimestampString: could not parse string \"" + str_date + "\" to Date object");
System.out.println(e.getClass().getCanonicalName());
System.err.println(e.getMessage());
System.exit(1);
return null;
}
}
}
Be sure to set the convertInvalidNumberToNa config (see near the top of this code) for the wrapper as well so that is nicely handles "NULL" strings. E.g.:
EasyPredictModelWrapper model = new EasyPredictModelWrapper(
new EasyPredictModelWrapper.Config()
.setModel(MojoModel.load(MODEL_CLASS_NAME))
.setConvertUnknownCategoricalLevelsToNa(true)
.setConvertInvalidNumbersToNa(true)
);

vaadin date format not formatting properly when data loaded with lazyquerycontainer and jpa

Hi I am using lazyquerycontainer integrated with jpa. As the entity manager loads the data some fields are in bigdecimal format but I want to show in date format. In the filtertable I have defined a decorator also but the format it is displaying is like 20,010,130.
Is it something I can do in the table itself?
Please help
Thank you.
If I have understood you correctly, tables can be overridden to do what you need:
Table t = new Table() {
#Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
Object v = property.getValue();
if (v instanceof Date) {
Date dateValue = (Date) v;
return "Formatted date: " + (1900 + dateValue.getYear())
+ "-" + dateValue.getMonth() + "-"
+ dateValue.getDate();
}
return super.formatPropertyValue(rowId, colId, property);
}
};
example from vaadin forum

Setting time zone when passing oracle.sql.ARRAY to PL/SQL procedure

I'm calling a plsql package procedure from Java. This procedure has an type parameter which carries a timestamp. When I'm setting a timestamp parameter directly to a procedure I can specify a Calendar object to declare the time zone to use e. g.
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
statement.setTimestamp(1, new Timestamp(calendar.getTimeInMillis()), calendar);
Is there a way to declare a timezone when using an oracle.sql.ARRAY or oracle.sql.STRUCT ?
The used types are declared as follows:
CREATE OR REPLACE TYPE "TY_EVENT_OBJECT"
AS
OBJECT
(
timestamp_event date,
state number(15),
parameter_name varchar2(248),
value number(15)
);
CREATE OR REPLACE TYPE "TY_EVENTS"
AS
TABLE OF TY_EVENT_OBJECT;
The Type TY_EVENTS is one parameter of the plsql procedure i have to use.
There is no way to simply pass a calendar which will be used for time zone conversion when you use user defined oracle types. When oracle.sql.ARRAY and oracle.sql.STRUCT are used, the ojdbc uses local calendar to convert java.sql.Date to oracle.sql.DATE so the actual date stored in database, in your case, is local time without timezone.
So if you want the date to be stored to database in UTC you will have to convert the java.sql.Date to oracle.sql.DATE manually by using UTC calendar.
Here is how you could do it:
Implement the SQLData interface and override the methods.
note:
-getSQLTypeName has to return the actual type name as defined in database, otherwise doesn't work.
-we use java.sql.Date below, it's important. So, if you want java.util.Date outside of TyEventObject you could create a setter/getter that does the conversion
public class TyEventObject implements SQLData {
private String sqlTypeName = "TY_EVENT_OBJECT";
private java.sql.Date timestampEvent;
private long state;
private String parameterName;
private long value;
#Override
public String getSQLTypeName() throws SQLException {
return sqlTypeName;
}
#Override
public void readSQL(SQLInput stream, String typeName) throws SQLException {
sqlTypeName = typeName;
// Reading date in UTC time
OracleJdbc2SQLInput oracleStream = (OracleJdbc2SQLInput) stream;
DATE oracleDate = (DATE)oracleStream.readOracleObject();
if( oracleDate != null) {
timestampEvent = oracleDate.dateValue( Calendar.getInstance(TimeZone.getTimeZone("UTC")));
} else {
timestampEvent = null;
}
state = stream.readLong();
parameterName = stream.readString();
value = stream.readLong();
}
#Override
public void writeSQL(SQLOutput stream) throws SQLException {
// Writing timestamp in UTC time
OracleSQLOutput oracleStream = (OracleSQLOutput) stream;
if( timestampEvent != null) {
DATE oracleDate = new DATE( timestampEvent, Calendar.getInstance(TimeZone.getTimeZone("UTC")));
oracleStream.writeOracleObject( oracleDate);
} else {
stream.writeDate( null);
}
stream.writeLong( state);
stream.writeString( parameterName);
stream.writeLong( value);
}
// add public getters and setters
}
Now you create an array of these TyEventObject objects to pass to plsql procedure like this (note that Array is java.sql.Array):
// I assume that your event objects that you want to save are in the list eventObjects
TyEventObject[] entries = new TyEventObject[ eventObjects.size()];
for( int i=0; i < eventObjects.size(); i++) {
entries[i] = new TyEventObject();
// You set the properties here
// entries[i].setTimestampEvent( eventObjects.get( i).getTimestampEvent());
}
Array dataObjectArray = connection.createArrayOf( "TY_EVENTS", entries);
And finally you call you plsql procedure like usual:
CallableStatement cs = connection.prepareCall("{call ProcedureName( ?)}");
cs.setObject(1, dataObjectArray, Types.ARRAY);
cs.execute();
cs.close();

How do i handle an empty jXDatePicker?

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
}

Categories

Resources