jtable takes "" into database when editing - java

here is my sample code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
String remark1 = (String) jTable1.getValueAt(row, 8);
String remark2 = (String) jTable1.getValueAt(row, 9);
String stock = (String) jTable1.getValueAt(row, 10);
String invoiceno =(String) jTable1.getValueAt(row, 11);
String id=(String) jTable1.getValueAt(row, 12);
System.out.println("remark1: "+remark1+" ,remark2: "+remark2+",stock:"+stock+", invoiceno:"+invoiceno+ " ,id: "+id);
when ever I open the jTable1 in edit mode and come out without entering text into it and perform the action ill get output like this
remark1: ,remark2: ,stock: , invoiceno: ,id: 7e3c63ffc9bc42dba8155270741d7c9a
and when i send that row to database at that fields its taking " at those fields.. which is creating me problem. how do i stop by not sending " into database when I just go into edit mode and come out of it without editing text/adding text
I tried adding this
line 426: if(invoiceno.equals("")){
invoiceno=null;
}
if i go into editmode of invoiceno jTable1 and come out, its passing argument invoiceno=null and working fine.
But if I dont go into that row(editmode) then send into database then its showing null java.lang.NullPointerException at line:426

You could reverse your validation, doing
if ("".equals(invoiceno)) {
invoiceno = null;
}
instead which would not throw a NullPointerException if invoiceno is null.

Related

Update data in JTable when data from a file used in the JTable is updated

So my JTable's data is from a text file. I have code in place to update that text file's information which works. However, I do not see additional rows in the JTable.
The way information is added to the text file is:
Clicking the Make appointment button and a dialog will appear.
The user will enter in relevant information.
Once information is entered the user presses ok which triggers the onOk function (in ScheduleAppointment.java) and writes information to the file.
private void onOK() {
// https://www.baeldung.com/java-string-to-date
String time = appointmentTimeField.getText();
String appointmentDate = appointmentDateField.getText() + " " + time;
String line = String.format("%s,%s,%s,%s,0\n", this.fname, this.lname, this.telephone, appointmentDate);
CSVReader reader = new CSVReader("./appointments.txt");
reader.writeAppointmentFile(line);
dispose();
}
Since I am using IntelliJ IDEA's form builder I have tried calling createUIComponent when the function that updates the text file is ran, it didn't work. So, I added a call to that function at the end of onOk
private void onOK() {
// https://www.baeldung.com/java-string-to-date
String time = appointmentTimeField.getText();
String appointmentDate = appointmentDateField.getText() + " " + time;
String line = String.format("%s,%s,%s,%s,0\n", this.fname, this.lname, this.telephone, appointmentDate);
CSVReader reader = new CSVReader("./appointments.txt");
reader.writeAppointmentFile(line);
createUIComponents(); // <-- Add this call to redraw the tables.
dispose();
}
Inside that function is a call to another function. createStaffAppointment(). This is what createStaffAppointment() looks like.
public void createStaffAppointment() {
CSVReader appointments = new CSVReader("./appointments.txt");
Vector<Vector<String>> columns = appointments.parseAppointmentFile(false);
Vector<String> names = new Vector<>();
names.add("Name");
names.add("Telephone");
names.add("Date");
staffTimetable = new JTable(columns, names);
}
I've also tried to use fireUpdateTableChanged on the table model. But, it didn't work as the table model didn't change. Only the text file where the data is taken from has changed.
The minimal reproducible example can be downloaded in dropbox here.

JTable when searched - not getting right ID

So I'm trying to after searching a name click on the table and then edit it in other table, the problem is that I'm not getting the right ID but instead only getting the ID that is the first.
JTable
Search in action
ID wrong
Edit Code
int linha = this.jTable1.getSelectedRow();
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));
Utilizador uti = UtilizadorJpaController.read(idUtilizador);
CriarCliente updateCliente = new CriarCliente(uti);
updateCliente.setVisible(true);
Search Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(model);
jTable1.setRowSorter(tr);
tr.setRowFilter(RowFilter.regexFilter(jTextField1.getText().trim(),1))
When you sort or filter a table, the data in the TableModel doesn't change. Only the view of the data changes.
If you want to get the data from the model, then you need to convert the "view row" to the "model row":
int linha = this.jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(linha);
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(modelRow, 0));
//int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));
Also, why are you using Integer.parseInt(...)? If the data in the model is an integer value, then it should be stored as an Integer value, not a String value.

Read empty cells from the table JTable into the array

I need to read data from the table JTable. The problem is that this table may contain empty cells. In this case the error message is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
How to avoid this error message?
mdArrivals = new QueryTableModelFS();
tbArrivals = new JTable(mdArrivals);
String STA = mdArrivals.getValueAt(i,1).toString();
Just check it, Read object mdArrivals.getValueAt(i,1) and after it check if not null call toString
Object value = mdArrivals.getValueAt(i,1);
if (value!=null)
{
String sta = value.toString();
}
String value= String.valueOf(jTable1.getValueAt(row, col));

Using JComboBox as a search box

Im using a JComboBox to search a query from a sql database. Here is my code.
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.removeAllItems();
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
sr.setSelectedItem(null);
sr.setPopupVisible(true);
System.out.println(sch);
}
sr = JComboBox
But when i type a letter in combobox, it adds all the items in database. I came to know that System.out.println(sch); always gives an empty string. And as soon as i type a letter, the text field of combo box becomes empty(i cant type a word with two letters). How to fix this? Thank you.
The reasons for your problems are the following:
sch is always empty is because you are calling sr.removeAllItems(); before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();. This means that the contents of the JComboBox is cleared (along with the selection) before you get what is selected.
Solution: Call sr.removeAllItems();AFTER you have got the selected item.
The combo box becomes empty because you call sr.setSelectedItem(null); at the end after you have repopulated it.
Solution: If you want the entered text then sr.getEditor().setItem(scr);
Only and idea but try to enclose the contents of the method in an if statement and check if the Enter key is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.
Use an ActionListener instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent when the editing is done.
When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.
Got the solution. This code works fine.
private void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
sr.removeAllItems();
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
sr.setSelectedItem(null);
sr.setPopupVisible(true);
((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
}
Thanks to Skepi,Kleopatra, Guillaume Polet

Can anyone help with a java problem regarding record stores?

I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?

Categories

Resources