How to Insert time in mysql using java - java

I'm doing a project to catering item hiring service. They want to save the date and time customer hire their items also save the date and time customer return them. Of course any of those not gona be actual at the movement date or time. So first of all I'm trying to find to save any date and time. Other activities will concern later. So I came up with little table. like given below.
ID | Name | Value | Date | Time
(int) | (Varchar) |( Double) | (DateTime) | (DateTime)
And I used this cord to save data.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
String date=new SimpleDateFormat("yyyy-MM-dd").format(dat.getDate());
String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];
try {
new JDBC().putData("INSERT INTO work (name, balance, date) VALUES ('"+txtName.getText()+"',"+txtValue.getText()+"', '"+date+"', '"+time+"') ");
JOptionPane.showMessageDialog(null, "value saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, this.getClass().getName() +" "+e);
}
}
When I'm entering data I'm having
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3" .
Help me to find the error of this cord and save any time. Actually I can save any date using String Date variable. I saved some demo data before I added time field to table. But I'm having this problem when I'm trying to save time. I am using date Spinner to save time. But I can't format it as HH-mm--ss. If you know another time saving feature please let me know. Please help me.

This line:
String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];
Is the same as this, just done on a single line
String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
String time = splitArr[3];
The error you are getting is saying that there is not 4 elements in the split array. Put in the below piece of code to debug what you are getting so you know what is happening in that single line
String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
for(int i = 0; i < splitArr.length; i++)
{
System.out.println("Element number " + i + " is \"" + splitArr[i] + "\"");
}
Then you can update your insert appropriately. Sorry I cant be of more help but we do not know what datespinner is or what datespinner.getValue() returns so do the above to help debug your code.

Related

How to fix "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" Android RFID 8500 Zebra

I am trying to develop and application to read and write to RF tags. Reading is flawless, but I'm having issues with writing. Specifically the error "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values"
I have tried reverse-engineering the Zebra RFID API Mobile by obtaining the .apk and decoding it, but the code is obfuscated and I am not able to decypher why that application's Write works and mine doesn't.
I see the error in the https://www.ptsmobile.com/rfd8500/rfd8500-rfid-developer-guide.pdf at page 185, but I have no idea what's causing it.
I've tried forcefully changing the writeData to Hex, before I realized that the API does that on its own, I've tried changing the Length of the writeData as well, but it just gets a null value. I'm so lost.
public boolean WriteTag(String sourceEPC, long Password, MEMORY_BANK memory_bank, String targetData, int offset) {
Log.d(TAG, "WriteTag " + targetData);
try {
TagData tagData = null;
String tagId = sourceEPC;
TagAccess tagAccess = new TagAccess();
tagAccess.getClass();
TagAccess.WriteAccessParams writeAccessParams = tagAccess.new WriteAccessParams();
String writeData = targetData; //write data in string
writeAccessParams.setAccessPassword(Password);
writeAccessParams.setMemoryBank(MEMORY_BANK.MEMORY_BANK_USER);
writeAccessParams.setOffset(offset); // start writing from word offset 0
writeAccessParams.setWriteData(writeData);
// set retries in case of partial write happens
writeAccessParams.setWriteRetries(3);
// data length in words
System.out.println("length: " + writeData.length()/4);
System.out.println("length: " + writeData.length());
writeAccessParams.setWriteDataLength(writeData.length()/4);
// 5th parameter bPrefilter flag is true which means API will apply pre filter internally
// 6th parameter should be true in case of changing EPC ID it self i.e. source and target both is EPC
boolean useTIDfilter = memory_bank == MEMORY_BANK.MEMORY_BANK_EPC;
reader.Actions.TagAccess.writeWait(tagId, writeAccessParams, null, tagData, true, useTIDfilter);
} catch (InvalidUsageException e) {
System.out.println("INVALID USAGE EXCEPTION: " + e.getInfo());
e.printStackTrace();
return false;
} catch (OperationFailureException e) {
//System.out.println("OPERATION FAILURE EXCEPTION");
System.out.println("OPERATION FAILURE EXCEPTION: " + e.getResults().toString());
e.printStackTrace();
return false;
}
return true;
}
With
Password being 00
sourceEPC being the Tag ID obtained after reading
Memory Bank being MEMORY_BANK.MEMORY_BANK_USER
target data being "8426017056458"
offset being 0
It just keeps giving me "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" and I have no idea why this is the case, nor I know what a "Word value" is, and i've searched for it. This is all under the "OperationFailureException", as well. Any help would be appreciated, as there's almost no resources online for this kind of thing.
Even this question is a bit older, I had the same problem so as far as I know this should be the answer.
Your target data "8426017056458" length is 13 and at writeAccessParams.setWriteDataLength(writeData.length()/4)
you are devide it with four. Now if you are trying to write the target data it is longer than the determined WriteDataLength. And this throws the Error.
One 'word' is 4 Hex => 16 Bits long. So your Data have to be filled up first and convert it to Hex.

ParseQuery fails to get object that exists in backend

reposting this question since I didn't get any responses the first time around. Parse doesn't appear to have any simple means of contacting them about this (which is frustrating), so I really hope someone here can help.
I am currently using Parse to create a messaging app. I have two fundamental ParseObjects in addition to the standard ParseUser, a Chatroom and a Message. A Chatroom contains pointers to the two users in the Chatroom. A Message contains the content of the Message, a pointer to the user who posted it, and a pointer to the Chatroom.
First, I create a list of all the Chatrooms that the current user is in. Then, I'm trying to create a second list of the most recent message in all of these Chatrooms (I have made it impossible to make a Chatroom without sending at least one Message first).
My code looks like this:
TextView mostRecent = (TextView) row.findViewById(R.id.mostRecent);
Date dt1 = null;
ParseQuery lastMessage = ParseQuery.getQuery("Message");
ParseObject chatroom = (ParseObject) roomList.get(position);
Log.w("Chatroom ObjectID...", room.getObjectId());
try {
lastMessage.whereEqualTo("chatroom", chatroom.fetchIfNeeded());
List<ParseObject> allMessages = lastMessage.find();
Log.w("# of Messages...", "Size of the list: " + allMessages.size() + ", Count of query: " + allMessages.count());
if (allMessages.size() > 0) {
mostRecent.setText((String) theList.get(theList.size() - 1).get("content"));
dt1 = allMessages.get(allMessages.size() - 1).getCreatedAt();
}
} catch (ParseException err) {
err.printStackTrace();
Log.w("PARSE ERROR", err.getMessage());
}
This code works for every Chatroom where the current user is the one who created the Chatroom and the Message in that Chatroom. However, whenever I have a different user attempt to start a Chatroom and send a Message to the original user, the code fails.
To be clear, the second user successfully creates both a Chatroom and a Message. I've verified that the Chatroom gets successfully added to the original user's list of Chatrooms, and that the Message contains a pointer to the correct Chatroom. However, for whatever reason, the Logs reveal a list size of 0 and a count of 0. I've even tried querying for the second user's exact message on the original user's account, and it claims the thing doesn't exist.
Any ideas? Could this have something to do with ACL? Thanks in advance!
NOTE: I've confirmed that both users are correctly included in the Message's ACL. What gives? Why isn't this working?
You need to wait for the query to fetch the data.
lastMessage.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> allMessages, ParseException e) {
if (e == null) {
Log.w("# of Messages...", "Size of the list: " + allMessages.size() + ", Count of query: " + allMessages.count());
} else {
Log.w("Exception thrown", e.getMessage());
}
}
}

Java Files.getLastModifiedTime Returning Unexpected Result

I'm writing a program that goes through files in a directory and checking each file's last modified date and comparing it with another variable. If the variable matches then I copy said file. I thought this was going to work like a charm but the last modified date being returned seems to be incorrect or there is a weird time zone thing happening.
I'm in the middle of a loop and the file currently being looked at is from 2014-08-18 and was actually last modified at 11:58 PM on that date but the getLastModifiedTime returns 2014-08-19T03:58:37.685611Z. So what gives???? Is this some kind of wacky time off set that I need to handle? This is important because if the last modified date is not accurate I won't know which file to copy....Anyone immediately know what's wrong? This is my first time using this way of iterating through files so I may be missing something.
//Creating a DirectoryStream inside a try-with-resource block
try (DirectoryStream<Path> ds =
Files.newDirectoryStream(FileSystems.getDefault().getPath(dir.getAbsolutePath()))) {for (Path p : ds) {
String lastMod = Files.getLastModifiedTime(p).toString();
String[] splitDte = lastMod.split("T");
if(dateSrc.equals(splitDte[0].toString()))
{
File fileToCopy = p.toFile();
copyFile(fileToCopy,
tempWorkingDir + "\\" + addLeadingZero(logM, 2) + ""
+ addLeadingZero(logDy, 2) + "\\" + fixedValue
+ "\\" + logType + "\\"
);
fileCountProcsd++;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
The Z indicates that the date is expressed in GMT.

Delay in retriving parent document using FT Search

i am using FT search on $message id field to retrieve the parent document.my database is FT indexed. i need the parent document for accepting the meeting invitation. how ever i am able to retrieve document after 2 hours of getting meeting invitation. need help.
String messageiD="<OFF0E85FF0.91FEF356-ON65257C97.00360343-65257C97.00361318#LocalDomain>";
if (messageiD.contains("#")) {
String[] strArr = messageiD.split("#");
messageiD = strArr[0].replace("<", "");
System.out.println("message id is "+messageiD);
//return messageiD;
}
String qry = "Field $MessageID CONTAINS " + messageiD;
DocumentCollection col1 = m_database.FTSearch(qry);
System.out.println("doc col length is " +col1.getCount());
Document docOld = col1.getFirstDocument();
System.out.println(docOld.getNoteID());
If you are able to retrieve the result one hour / two hours later, then the FT- Index is not up to date, when it tries to process your request. Use method updateFTIndex() of NotesDatabase- class to make sure, it is up to date. Of course you can check, if it IS up to date, using getLastFTIndexed()- Method... Here is example- code from the Designer- Help to use these two methods:
try {
Session session = getSession();
AgentContext agentContext =
session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
String title = db.getTitle();
DateTime lastDT = db.getLastFTIndexed();
DateTime nowDT = session.createDateTime("Today");
nowDT.setNow();
int daysSince =
nowDT.timeDifference(lastDT) / 86400;
if (daysSince > 2) {
System.out.println("Database \"" + title +
"\" was last full-text indexed " +
daysSince + " days ago");
System.out.println("Updating");
db.updateFTIndex(true); }
else
System.out.println("Database \"" + title +
"\" was full-text indexed less
than two days ago");
} catch(Exception e) {
e.printStackTrace();
}
Additional Information: When creating a fulltext index for a database you define, how often this index is updated.
But: Even when selecting "Immediate" in the dialog, this does not mean, that the index will always be up to date. Updating the fulltext is a job of the Update- task of the server. If this task is to "busy" then the request is queued and might be delayed for some time until there are resources available for doing the job.
The performance of fulltextindex updates can be enhanced by the server admin by setting a notes.ini- Variable "UPDATE_FULLTEXT_THREAD" (see this link about the variable to check details).

retry open files in directory

I am trying the following code to open files in a certain directory. The name of the files are assigned by date but some dates are missing. I want to iterate through the dates to get the files and make the code go back 1 day every time it fails to find a file until it finally finds one (currentdate is a global variable and the strange xml element is because I'm using processing).
What I think the code should do is:
try to open the file with the given date.
on error, it goes to catch and gets a new date.
the process is repeated until a valid date is found.
when a valid date is found it goes to the line where break is and exits the loop.
But for some reason it does weird stuff like EDIT # sometimes it jumps too much, especially near the first month #
Is my logic not working for some reason?
Thanks
String strdate=getdatestring(counter);
int counter=0;
while(true){
try{
xmldata = new XMLElement(this, "dir/" + strdate + "_filename.xml" );
break;
}catch(NullPointerException e){
counter +=1;
strdate=getdatestring(counter);
}}
String getdatestring(int counter) {
Date firstdate=new Date();
int daystosum=0;
String strcurrentdate="";
if(keyPressed && key=='7'){
daystosum=-7;
}
daystosum=daystosum-counter;
Calendar c=Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try{
firstdate=formatter.parse("2012-04-13");//first day of the database
}catch(ParseException e){
println(e);
}
c.setTime(currentdate);
c.add(Calendar.DATE,daystosum);
currentdate=c.getTime();
if(currentdate.before(firstdate)){
currentdate=firstdate;
}
strcurrentdate=formatter.format(currentdate);
return strcurrentdate;
}
I believe once you do this,
daystosum=daystosum-counter;
you need to reset the counter as
counter = 0;
otherwise next time it will subtract more bigger number e.g. to start, say daystosum is 0 and counter is 5, after the daystosum=daystosum-counter;, daystosum will become -5. Again you go in the while loop and file is not found then count will increase to 6. In that case you would be getting `daystosum=daystosum-counter; as -5-6 = -11, but you would want it to move to -6. Resetting the counter should ix your issue.
On the other note, I think you can list down the files using file.listFiles() from the parent directory and perform the search on the file names. In that case, you are not attempting to open files again and again.

Categories