Read empty cells from the table JTable into the array - java

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));

Related

How to Handle NoSuchElementException for empty element.and still execute next line of code?

i am trying to get text of dynamic web table to excel sheet , sometimes text is present in rows of column and sometime it is not.. when text is present in the table row , i want to get text of that cell..using getText Method, But when Text is not present i want to write empty text and keep cell blank.. But it is giving NoSuchElementException.. how to handle that..?? any help would be appreciated.. thanks in advance..
String actualXpath_SL = beforeXpath_SL + j + afterXpath_SL;
String SL = driver.findElements(By.xpath(actualXpath_SL)).getText()
currentRow.createCell(0).setCellValue(SL);
To continue your programme when selenium doesn't find an element you can do two things.
Put the code inside a try block and handle the NoSuchElementException in the catch block.
String OneA = "";
try{
//find element
OneA = driver.findElement(By.xpath(actualXpath_1A)).getText();
}catch (NoSuchElementException e){
//stacktrace and other code after catching the exception
e.printStackTrace();
}
Or, you can use findElements and check the returned list is empty or not.
List<WebElement> elements = driver.findElements(By.xpath(actualXpath_1A));
String OneA = "";
if(!elements.isEmpty()){
OneA = elements.get(0).getText();
} else {
//Handle if no element present
}
the second solution avoids the exception and it is faster than waiting for the exception.
You should use .size()>0 rather isEmpty()
String actualXpath_2S = beforeXpath_2S + j + afterXpath_2S;
List<WebElement> eight = driver.findElements(By.xpath(actualXpath_2S));
String TwoS="";
if(eight.size()>0){
TwoS = eight.get(0).getText();
}
You have to update the logic for all if conditions that are using isEmpty.

Getting true selected value of JTable

I'm currently getting the value of my jTable as everybody does:
String d = jTable1.getModel().getValueAt( jTable1.getSelectedRow() , row ).toString();
The thing is that now I'm sorting my jTable with a rowsorter:
sorter = new TableRowSorter<TableModel>(modelo);
jTable1.setRowSorter(sorter);
private void filterTable(){
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter("(?iu)"+jFilter.getText(),0,1,2,3,4);//no filtrar la columna con imágenes porque hace cualquiera
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
THE PROBLEM:
Once the table is filtered, the function getSelectedRow returns the correct row, but the getModel function returns the original model, not the one after filtering...
THE QUESTION:
How to get the correct value from the table when it is filtered?
You probably need to convert your "row" value to a model index value, using convertRowIndexToModel.
String d = Table1.getModel().getValueAt(convertRowIndexToModel(jTable1.getSelectedRow()) , column ).toString();
For future wanderers:
The problem was on the way of getting the value from the jTable:
This is wrong when you have a rowsorter:
String d = jTable1.getModel().getValueAt( jTable1.getSelectedRow() , row ).toString();
This is what you should be doing:
String d = jTable1.getValueAt( jTable1.getSelectedRow() , row ).toString();

InvalidTypeException: Invalid type for value 1 of CQL type text, expecting class java.lang.String but class [Ljava.lang.Object; provided

I am trying to insert into Cassandra database using Datastax Java driver. But everytime I am getting below exception at prBatchInsert.bind line-
com.datastax.driver.core.exceptions.InvalidTypeException: Invalid type for value 1 of CQL type text, expecting class java.lang.String but class [Ljava.lang.Object; provided
Below is my method which accepts userId as the input and attributes as the Map which contains key as my Column Name and value as the actual value of that column
public void upsertAttributes(final String userId, final Map<String, String> attributes, final String columnFamily) {
try {
Set<String> keys = attributes.keySet();
StringBuilder sqlPart1 = new StringBuilder(); //StringBuilder.append() is faster than concatenating Strings in a loop
StringBuilder sqlPart2 = new StringBuilder();
sqlPart1.append("INSERT INTO " + columnFamily + "(USER_ID ");
sqlPart2.append(") VALUES ( ?");
for (String k : keys) {
sqlPart1.append(", "+k); //append each key
sqlPart2.append(", ?"); //append an unknown value for each key
}
sqlPart2.append(") "); //Last parenthesis (and space?)
String sql = sqlPart1.toString()+sqlPart2.toString();
CassandraDatastaxConnection.getInstance();
PreparedStatement prBatchInsert = CassandraDatastaxConnection.getSession().prepare(sql);
prBatchInsert.setConsistencyLevel(ConsistencyLevel.ONE);
// this line is giving me an exception
BoundStatement query = prBatchInsert.bind(userId, attributes.values().toArray(new Object[attributes.size()])); //Vararg methods can take an array (might need to cast it to String[]?).
CassandraDatastaxConnection.getSession().executeAsync(query);
} catch (InvalidQueryException e) {
LOG.error("Invalid Query Exception in CassandraDatastaxClient::upsertAttributes "+e);
} catch (Exception e) {
LOG.error("Exception in CassandraDatastaxClient::upsertAttributes "+e);
}
}
What wrong I am doing here? Any thoughts?
You need to combine the userId string to the object array, because the way you are passing it now is being seen as [string, object array] and java doesn't like that.
// instead of
// BoundStatement query = prBatchInsert.bind(userId, attributes.values().toArray(new Object[attributes.size()]));
// try, first combining the uid to the map of values
Collection<Object> params = new ArrayList<Object>(attributes.size() + 1);
params.add(userId);
for(Object o : attributes.values().toArray())
params.add(o);
// then passing in the new collection as an array
BoundStatement query = prBatchInsert.bind(params.toArray());

jtable takes "" into database when editing

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.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String.

This is My code:
Workbook workbook = new Workbook();
workbook.open(filename);
Worksheet worksheet = workbook.getWorksheets().getSheet(sheetno);
Cells cells=worksheet.getCells();
int num=cells.getMaxDataRow();
int num1=cells.getMaxDataColumn();
int OCount=1;
for (int n1=startpos+1;n1<endpos;n1++)
{ if (cells.checkCell(n1, Colno).getValue()==null )
{ Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style);
} else if(cells.checkCell(n1, Colno).getValue().toString().length()==0) { Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.TEAL);
cell.setStyle(style); } else{ double intCounter = Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
System.out.println(cells.checkCell(n1,Colno).getValue().toString());
if(intCounter!=Count){
Cell cell=cells.getCell(n1,Colno);
Style style = cells.getCell( n1,Colno).getStyle();
style.setColor(Color.YELLOW);
cell.setStyle(style);
}
}
Count=Count+1;
} workbook.save("C:\\output.xls",FileFormatType.EXCEL97TO2003);
I am trying to check that Sr no is in sequential order or not. it is working fine if there is no empty string " ". For empty string it throws
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String.
Thanks in Advance....
The problem is this line of code:
Double.parseDouble(cells.checkCell(n1,Colno).getValue().toString());
There you try to make a Double out of an empty String. Check the documentation and you will see that the NumberFormatException is the intended behavior. So you either have to check first if the String is empty or implement proper error handling.
Here a quote from the API for the method Double.parseDouble(...):
Throws: NumberFormatException - if the string does not contain a
parsable double.
its better to handle these cases by using a utility method.
private Double getCorrectedDouble(CellValues... ){
//check and handle empty fields
//return new Double(0) if the target is empty
}

Categories

Resources