This question already has answers here:
null pointer exception apache poi
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
public class ExecuteTest {
#Test
public void testLogin() throws Exception {
// TODO Auto-generated method stub
`WebDriver webdriver = new FirefoxDriver();
ReadExcelFile file = new ReadExcelFile();
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
//Read keyword sheet
Sheet RDSheet = file.readExcel(System.getProperty("user.dir")+"\\","TestCase.xlsx" , "KeywordFramework");
//Find number of rows in excel file
int rowCount = //Loop over all the rows RDSheet.getLastRowNum()-RDSheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 1; i < rowCount+1; i++) {
Row row = RDSheet.getRow(i);
//Check if the first cell contain a value, if yes, That means it is the new testcase name
if(row.getCell(0).toString().length()==0){
//Print testcase detail on console
System.out.println(row.getCell(1).toString()+"----"+ row.getCell(2).toString()+"----"+
row.getCell(3).toString()+"----"+ row.getCell(4).toString());
//Call perform function to perform operation on UI
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(),
row.getCell(3).toString(), row.getCell(4).toString());
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0).toString() +" Started");
}
}
}
}
getting null pointer exception when first cell is empty.
I have searched many blogs but couldn't find any solution
can anyone please help me with code.
for every .toString() add a " "+ x.toString() to it, so that the value doesnt become a null.
`
for (int i = 1; i < rowCount+1; i++) {
Row row = RDSheet.getRow(i);
//Check if the first cell contain a value, if yes, That means it is the new testcase name
if((row.getCell(0)+"").toString().length()==0){
//Print testcase detail on console
System.out.println((row.getCell(1)+"").toString()+"----"+ (row.getCell(2)+"").toString()+"----"+
(row.getCell(3)+"").toString()+"----"+ (row.getCell(4)+"").toString());
//Call perform function to perform operation on UI
//your operations
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0).toString() +" Started");
}
}
`
Make sure you add a null check before using toString() method otherwise you will get NPE if the value is null.
if (row.getCell(0) != null) {
row.getCell(0).toString() //in this case you are trying to call toString on null value.
}
Refer this SO question
try below Code its working fine for me, we cannot define length of a Null
if(row.getCell(0)==null){
//Print testcase detail on console
//System.out.println("testing");
System.out.println(row.getCell(1)+"----"+ row.getCell(2)+"----"+
row.getCell(3)+"----"+ row.getCell(4));
//Call perform function to perform operation on UI
try{
operation.perform(allObjects, row.getCell(1)==null?"Not a Valid KeyWord":row.getCell(1).toString(),
row.getCell(2)==null?null:row.getCell(2).toString(),
row.getCell(3)==null?null:row.getCell(3).toString(),
row.getCell(4)==null?null:row.getCell(4).toString());
}catch(Exception e)
{
//will print Error Row and break the flow
System.out.println(i);
System.out.println(e);
break;
}
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0) +" Started");
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at dacia.Principale.jButton10ActionPerformed(Principale.java:1204)
at dacia.Principale.access$500(Principale.java:44)
Code:
XSSFWorkbook wg= new XSSFWorkbook();
XSSFSheet sht=wg.createSheet();
TreeMap<String,Object[]> data= new TreeMap<>();
// data.put("-1",new Object[]){"chasis","marque","couleur","nom client","date d entree","date sortie","telephone","numero WW","position","mode paiment","gamme","version"});
data.put("-1",new Object[]{jTable2.getColumnName(0),jTable2.getColumnName(1),jTable2.getColumnName(2),jTable2.getColumnName(3),jTable2.getColumnName(4),jTable2.getColumnName(5),jTable2.getColumnName(6),jTable2.getColumnName(7),jTable2.getColumnName(8),jTable2.getColumnName(9),jTable2.getColumnName(10),jTable2.getColumnName(11)});
for(int i=0;i<jTable2.getRowCount();i++)
{
data.put(Integer.toString(i),new Object[]{jTable2.getValueAt(i,0).toString(),jTable2.getValueAt(i,1).toString(),jTable2.getValueAt(i,2).toString(),jTable2.getValueAt(i,3).toString(),jTable2.getValueAt(i,4).toString(),jTable2.getValueAt(i,5).toString(),jTable2.getValueAt(i,6).toString(),jTable2.getValueAt(i,7).toString(),jTable2.getValueAt(i,8).toString(),jTable2.getValueAt(i,9).toString(),jTable2.getValueAt(i,10).toString(),jTable2.getValueAt(i,11).toString()});
}
//write to excel
Set <String> ids=data.keySet();
XSSFRow row ;
int roow=0 ;
for (String st : ids)
{
row=sht.createRow(roow++);
Object[] values=data.get(st);
int cellId=0 ;
for(Object o : values)
{
Cell cell=row.createCell(cellId++);
cell.setCellValue(o.toString());
}
}
try {
//write to file
FileOutputStream fos= new FileOutputStream(new File("/home/elprincipe/Desktop/dacia.xls"));
wg.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Principale.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Principale.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is in:
data.put(Integer.toString(i),new Object[]{jTable2.getValueAt(i,0).toString(),jTable2.getValueAt(i,1).toString(),jTable2.getValueAt(i,2).toString(),jTable2.getValueAt(i,3).toString(),jTable2.getValueAt(i,4).toString(),jTable2.getValueAt(i,5).toString(),jTable2.getValueAt(i,6).toString(),jTable2.getValueAt(i,7).toString(),jTable2.getValueAt(i,8).toString(),jTable2.getValueAt(i,9).toString(),jTable2.getValueAt(i,10).toString(),jTable2.getValueAt(i,11).toString()});
From what I can tell by your code, something in your jTable2 is not getting initialized properly.
The idea of a NullPointerException is that you are trying to use an object that hasn't been created yet. Since you are able to iterate over the jTable2, and you don't have an index out of bounds exception, I would say that one of the elements of the jTable2 is not being created
What I would suggest is going over this in the debugger, carefully analyzing each row of the table before you try to convert it to a String
Also, (this is more of a style thing, but I think it'll help you in the long run) you should move this sort of functionality into another method, so that it'll be easier to read:
for(int i = 0; i < jTable2.getRowCount(); i++) {
data.put(convertRow(jTable2, i));
}
public Object[] convertRow(Table jTable2, int row) {
rowLength = jTable2[0].length;
Object[] row = new Object[rowLength];
for (int i = 0; i < rowLength; i++) {
Object datum = jTable2.getValueAt(row, i);
if (datum != null) {
row[i] = datum.toString();
}
else {
row[i] = "Null entry"
}
}
return row
}
I promise you this will make debugging much much easier
Java documentation https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#put-K-V-:
Returns: the previous value associated with key, or null if there was
no mapping for key. (A null return can also indicate that the map
previously associated null with key.)
NullPointerException - if the specified key is null and this map uses
natural ordering, or its comparator does not permit null keys
I have no idea what your trying to put in.. but i would check if you might be putting in a null value.
I am working with Jackcess to read and categorize an access database. It's simply meant to open the database, loop through each line, and print out individual row data to the console which meet certain conditions. It works fine, except for when I try to read numeric values. My code is below. (This code is built into a Swing GUI and gets executed when a jbutton is pressed.)
if (inv == null) { // Check to see if inventory file has been set. If not, then set it to the default reference path.
inv = rPath;
}
if (inventoryFile.exists()) { // Check to see if the reference path exists.
List<String> testTypes = jList1.getSelectedValuesList();
List<String> evalTypes = jList3.getSelectedValuesList();
List<String> grainTypes = jList2.getSelectedValuesList();
StringBuilder sb = new StringBuilder();
for (int i=0; i<=evalTypes.size()-1; i++) {
if (i<evalTypes.size()-1) {
sb.append(evalTypes.get(i)).append(" ");
}
else {
sb.append(evalTypes.get(i));
}
}
String evalType = sb.toString();
try (Database db = DatabaseBuilder.open(new File(inv));) {
Table sampleList = db.getTable("NTEP SAMPLES LIST");
Cursor cursor = CursorBuilder.createCursor(sampleList);
for (int i=0; i<=testTypes.size()-1; i++) {
if ("Sample Volume".equals(testTypes.get(i))) {
if (grainTypes.size() == 1 && "HRW".equals(grainTypes.get(0))) {
switch (evalType) {
case "GMM":
for (Row row : sampleList){
if (null != row.getString("CURRENTGAC")) {}
if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}
}
break;
case "NIRT":
// some conditional code
break;
case "TW":
// some more code
break;
}
}
else {
JOptionPane.showMessageDialog(null, "Only HRW samples can be used for the selected test(s).", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
}
catch (IOException ex) {
Logger.getLogger(SampleFilterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
When the code is run I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
The following condition looks to be what is throwing the error.
row.getDouble("CURRENTGAC")>=12.00
It appears that when the data is read from the database, the program is reading everything as a string, even though some fields are numeric. I was attempting to cast this field as a double, but java doesn't seem to like that. I have tried using the Double.parseDouble() and Double.valueOf() commands to try converting the value (as mentioned here) but without success.
My question is, how can I convert these fields to numeric values? Is trying to type cast the way to go, or is there a different method I'm not aware of? You will also notice in the code that I created a cursor, but am not using it. The original plan was to use it for navigating through the database, but I found some example code from the jackcess webpage and decided to use that instead. Not sure if that was the right move or not, but it seemed like a simpler solution. Any help is much appreciated. Thanks.
EDIT:
To ensure the program was reading a string value from my database, I input the following code
row.get("CURRENTGAC").getClass().getName()
The output was java.lang.String, so this confirms that it is a string. As was suggested, I changed the following code
case "GMM":
for (Row row : sampleList){
if (null != row.get("CURRENTGAC"))
//System.out.println(row.get("CURRENTGAC").getClass().getName());
System.out.println(String.format("|%s|", row.getString("CURRENTGAC")));
/*if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00 && row.getDouble("CURRENTGAC")<=14.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}*/
}
break;
The ouput to the console from these changes is below
|9.85|
|11.76|
|9.57|
|12.98|
|10.43|
|13.08|
|10.53|
|11.46|
...
This output, although looks numeric, is still of the string type. So when I tried to run it with my conditional statement (which is commented out in the updated sample code) I still get the same java.lang.ClassCastException error that I was getting before.
Jackcess does not return all values as strings. It will retrieve the fields (columns) of a table as the appropriate Java type for that Access field type. For example, with a test table named "Table1" ...
ID DoubleField TextField
-- ----------- ---------
1 1.23 4.56
... the following Java code ...
Table t = db.getTable("Table1");
for (Row r : t) {
Object o;
Double d;
String fieldName;
fieldName = "DoubleField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %f",
o));
System.out.println();
fieldName = "TextField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %s",
o));
try {
d = r.getDouble(fieldName);
} catch (Exception x) {
System.out.println(String.format(
"r.getDouble(\"%s\") failed - %s: %s",
fieldName,
x.getClass().getName(),
x.getMessage()));
}
try {
d = Double.parseDouble(r.getString(fieldName));
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) succeeded. Value: %f",
fieldName,
d));
} catch (Exception x) {
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) failed: %s",
fieldName,
x.getClass().getName()));
}
System.out.println();
}
... produces:
DoubleField comes back as: java.lang.Double
Value: 1.230000
TextField comes back as: java.lang.String
Value: 4.56
r.getDouble("TextField") failed - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
Double.parseDouble(r.getString("TextField")) succeeded. Value: 4.560000
If you are unable to get Double.parseDouble() to parse the string values from your database then either
they contain "funny characters" that are not apparent from the samples you posted, or
you're doing it wrong.
Additional information re: your sample file
Jackcess is returning CURRENTGAC as String because it is a Text field in the table:
The following Java code ...
Table t = db.getTable("NTEP SAMPLES LIST");
int countNotNull = 0;
int countAtLeast12 = 0;
for (Row r : t) {
String s = r.getString("CURRENTGAC");
if (s != null) {
countNotNull++;
Double d = Double.parseDouble(s);
if (d >= 12.00) {
countAtLeast12++;
}
}
}
System.out.println(String.format(
"Scan complete. Found %d non-null CURRENTGAC values, %d of which were >= 12.00.",
countNotNull,
countAtLeast12));
... produces ...
Scan complete. Found 100 non-null CURRENTGAC values, 62 of which were >= 12.00.
I managed to display 1 record of the asked category but what i need is for the program to display everything from that category. If it's too vague the code might help. Thanks in advance
public static void SearchCatRecord() throws Exception
{
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------SEARCH CATEGORIZED ITEM--------");
System.out.println("\n\t\t\t*******************************");
System.out.print("\t\t\tEnter Category: ");
String searchnum = br.readLine();
boolean found = false;
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
found = true;
System.out.println("\n\n\t\t\tSearch Completed");
exiting();
}
}
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
exiting();
}
MainMenu();
}
The following code asks the user which category should the program display. then it displays the asked category but it only displays one record.
This is because you call exiting(); when you found the first record. You should remove it in your loop.
for example:
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
}
}
System.out.println("\n\n\t\t\tSearch Completed");
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
}
exiting();
If you want to find all the records then you should not breakout after finding one record that meets your criteria. I believe your method invocation exiting() is not needed in loop.
On a side note why are you setting found=true twice in the loop? Also what is the need of Thread.sleep(2000) in the code?
I have code:
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
for(WebElement position_list : some_list.getOptions()) {
if(position_list.getText().equalsIgnoreCase(v_value)) {
some_list.selectByVisibleText(position_list.getText());
break;
}
}
}
How can I add condition: if selenium doesn't find position_list.getText().equalsIgnoreCase(v_value) then system throw new RuntimeExpression?
Use iterator instead of foreach, it provides a hasNext() method with which you can check if you are currently dealing with the last element of your list.
Iterator<WebElement> iterator = some_list.getOptions().iterator();
and then instead of your foreach:
while(iterator.hasNext()) {
WebElement current = iterator.next();
if(current.getText().equalsIgnoreCase(v_value)) {
current.selectByVisibleText(position_list.getText());
break;
}
if(!iterator.hasNext()){
throw new RuntimeException();
}
}
Just a suggestion from what I see in your code.
When you use some_list.selectByVisibleText(position_list.getText()); the selectByVisibleText(..) method is already setup to iterate over all available options and select the one that matches the text parameter you pass in. Putting the call inside a loop checking for the option to be available is not ideal if you are looking to throw an exception.
Also, let's say you have the following code -
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
some_list.selectByVisibleText(position_list.getText());
....
}
In this case selectByVisibleText would throw a NoSuchElementException("Cannot locate element with text: " + text); in case the option is not available for selection. You should be able to catch that and throw a runtime exception.
I guess a simple answer to your question is a try catch
public void setList(By localizator, String v_value {
Select some_list = new Select(driver.findElement(localizator));
for(WebElement position_list : some_list.getOptions()) {
try{
if(position_list.getText().equalsIgnoreCase(v_value)) {
some_list.selectByVisibleText(position_list.getText());
break;
}
}
catch(RuntimeExpression ex)
{
...
}
}
}
I am having trouble with the logic of deleting an entry in an Address Book... I am saving all the entries using an ARRAY.
I am try to make the array[i] = null, if array[i] is equals to the entered name of the user. But after i delete an entry and then try to view all entries again, nothing shows.. and output says :
Exception in thread "main" java.lang.NullPointerException
at AddressBook.viewAll(AddressBook.java:61)
at AddressBook.main(AddressBook.java:35)
Java Result: 1
this is my code in deleting an Entry:
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
//JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
}
}
}
Can you help me figure out what was wrong with my code... or LOGICAL ERROR?
If you have any suggestion or better way to delete an entry that would be a big help..
please help...
if (entry[i].getName().equals(SName)) {
if on one pass you make
entry[i] = null
then how would you getName() afterwords?
try adding a null check to your if statement
if (entry[i] != null && entry[i].getName().equals(SName)) {
EDIT: Benjamin brings up a good point. You should be prepared for a null result from showinputdialog(). For example, there's a cancel button right? If they press that, you'll get null I believe. Here's some better code for that case:
public void deleteEntry() {
/* get the input */
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
/* if no input, nothing to delete */
if(SName == null) return;
/* find the name */
for (int i = 0; i < counter; i++) {
/* make sure we have an entry*/
/* we know SName is not null */
if (entry[i] != null && SName.equals(entry[i].getName())) {
/* null out the deleted entry */
entry[i] = null;
// break; /* If you know you have unique names, you can leave the for loop now */
} /* end if */
} /* end for i*/
}