Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException TreeMap [duplicate] - java

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.

Related

Java Sellinum Cucumber Excell data driven

Need to get "value" based on given "key" from Excel file
I have excel file
File name Test xlsx
and sheet name sheet1
And sheet contains following key and value pairs and. JIRA ticket is unique .
Test case description
testdata key
Testdatavalue
testdata2 key
Testdata2 Value
testdata3 key
Testdata3 value
Sampiletest description1
Testcase-jira-1
user1id
Harshadh
Password
123ggg
Sampiletest2 discription
Testcase-jira-2
user2
Ramu
Password123
333ggg
Sampiletest3 discription
Test case jira-3
user3
latha
Password556
73hhh
Up to N number of rows
Here, I needs to get the data in following way by using Java Selenium Cucumber. I am going to use above test data to pass in Cucumber step definition class file by BDD way.
How can we get the data in definition file for following way
1)If pass Key value from current row how can we get the value of value for provide test input for webSeleinum element
Example 4th row data
Sampiletest3 discription|Test case jira-3| user3|latha|Password556|73hhh
.....
If I call the "user3" that should return "Password556"
Same way any row I need to get the value.
Please guide me
You can try the below code.
Feature file:
In examples, you can give the row numbers and sheet name to use the data for itterations.
Scenario Outline: Login to the application with multiple users.
Given get data from datasheet with "<test_id>" and "<sheetName>"
And login to the application
Examples:
| test_id | sheetName |
| 1 | Login |
| 2 | Login |
Excel data:
Read the data from excel and store it in a hashmap:
Create a class to read the data (Example: ExcelReader)
Use org.apache.poi.ss.usermodel and org.apache.poi.xssf.usermodel imports
public class ExcelReader {
private File file;
private FileInputStream inputStream;
private String testID;
private String sheetName;
private int testIdColumn;
private int numberOfColumns;
private XSSFCell cell;
public HashMap<String, String> fieldsAndValues;
public ExcelReader(String testId, String sheetName) {
file = new File(System.getProperty("user.dir") + "Excel location path");
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("File not found at given location: " + e);
}
this.testID = testId;
this.sheetName = sheetName;
this.readExcelAndCreateHashMapForData();
}
public HashMap<String, String> readExcelAndCreateHashMapForData() {
try {
fieldsAndValues = new HashMap<String, String>();
XSSFWorkbook workBook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workBook.getSheet(sheetName);
/* Get number of rows */
int lastRow = sheet.getLastRowNum();
int firstRow = sheet.getFirstRowNum();
int numberOfRows = lastRow - firstRow;
/*
* Get test_Id column number.
*/
outerloop: for (int row = 0; row < numberOfRows; row++) {
numberOfColumns = sheet.getRow(row).getLastCellNum();
for (int cellNumber = 0; cellNumber < numberOfColumns; cellNumber++) {
cell = sheet.getRow(row).getCell(cellNumber);
cell.setCellType(Cell.CELL_TYPE_STRING);
if (sheet.getRow(row).getCell(cellNumber).getStringCellValue().equalsIgnoreCase("test_ID")) {
testIdColumn = sheet.getRow(row).getCell(cellNumber).getColumnIndex();
break outerloop;
}
}
}
/*
* Search for the test id value.
*/
outerloop: for (int i = 0; i <= numberOfRows; i++) {
cell = sheet.getRow(i).getCell(testIdColumn);
cell.setCellType(Cell.CELL_TYPE_STRING);
if (testID.equals(sheet.getRow(i).getCell(testIdColumn).getStringCellValue())) {
for (int j = 0; j < numberOfColumns; j++) {
XSSFCell key = sheet.getRow(testIdColumn).getCell(j);
XSSFCell value = sheet.getRow(i).getCell(j);
key.setCellType(Cell.CELL_TYPE_STRING);
if (value == null) {
// Not capturing blank cells.
} else if (value.getCellType() == XSSFCell.CELL_TYPE_BLANK) {
// Not capturing blank cells.
} else {
value.setCellType(Cell.CELL_TYPE_STRING);
String fieldName = sheet.getRow(testIdColumn).getCell(j).getStringCellValue().trim();
String fieldValue = sheet.getRow(i).getCell(j).getStringCellValue().trim();
fieldsAndValues.put(fieldName, fieldValue);
}
}
System.out.println("Fields and values: " + Arrays.toString(fieldsAndValues.entrySet().toArray()));
break outerloop;
}
}
} catch (Exception e) {
System.out.println("Exception occurred at getting the sheet: " + e);
}
/* Return the hash map */
return fieldsAndValues;
}
}
StepDefinition:
ExcelReader excelReader;
#Given("get data from datasheet with \"(.*)\" and \"(.*)\"$")
public void get_data_from_datasheet(String testId, String sheetName) {
excelReader = new ExcelReader(testId, sheetName);
}
#And("login to the application")
public void loginApplication(){
driver.findElement(By.xpath("element")).sendKeys(excelReader.fieldsAndValues.get("UserName"));
driver.findElement(By.xpath("element")).sendKeys(excelReader.fieldsAndValues.get("PassWord"));
driver.findElement(By.xpath("element")).click();
}
I would recommend putting all the data for a scenario inside of Gherkin documents, but you might have a valid use cases for pulling data from excel. However, in my experience, these type of requirements are rare. The reason why it is not recommended is, your BDD feature files are your requirements and should contain the right level of information to document the expected behavior of the system. If your data comes from an excel, then it just makes the requirement reading bit more difficult and makes it difficult to maintain.
Saying that if there is a strong reason for you to have these data stored in excel, you could easily achieve this using NoCodeBDD. All you have to do is map the column names and upload the excel and the tool take care of the rest. Please check this .gif to see how it is done. https://nocodebdd.live/examples-using-excel
Disclaimer: I am the founder of NoCodeBDD.
If you are using Junit5 here is an example on how it is done https://newbedev.com/data-driven-testing-in-cucumber-using-excel-files-code-example
You can use external data-source to provide examples using qaf-cucumber. It will enable to provide data-file to be used to provide examples from external data-source, which includes csv, json, xml, excel file or database query.
We cannot directly integrete Excel file data to Gerkin file
.
Instead write separate method in step file to get data from excel and do your cases.
I use following code get the data - common code
public static JSONArray Read_Excel_Data(String filename, String sheetname) throws IOException {
FileInputStream fileIn = null;
Workbook workbookout = null;
JSONArray totalData = new JSONArray();
try{
log.info("Filename and Sheet name : "+filename+", "+ sheetname );
fileIn = new FileInputStream(new File(filename));
workbookout = new XSSFWorkbook(fileIn);
Sheet sh = workbookout.getSheet(sheetname);
int totRows = sh.getLastRowNum();
Row hearderRow = sh.getRow(0);
int totCols = hearderRow.getLastCellNum();
log.info("Total [ Rows and Colums ] : [ "+totRows+" and "+ totCols +" ] ");
for(int i=1; i <= totRows; i++ ){
log.info("Progressing row : "+i);
Row tempRw = sh.getRow(i);
JSONObject jo = new JSONObject();
for(int j=0; j<totCols; j++ ){
Cell tempCell = tempRw.getCell(j);
Cell HeaderCell = hearderRow.getCell(j);
try{
jo.put(HeaderCell.getStringCellValue(), tempCell.getStringCellValue());
log.info("Value in "+i+" / "+j+" :::::::::::: > "+tempCell.getStringCellValue() );
}catch (NullPointerException npe){
log.warn(":::::::::::: > Null Value in [ "+i+" / "+j+" ] ");
}
}
totalData.add(jo);
}
workbookout.close();
fileIn.close();
System.out.println("Total data :::::::: "+totalData.toJSONString());
}catch(Exception e){
e.printStackTrace();
log.error("Error Occured !!"+e.toString());
workbookout.close();
fileIn.close();
}
return totalData;
}

how can I append two list with different type? [duplicate]

This question already has answers here:
Two different ArrayList merge? [closed]
(2 answers)
Closed 4 years ago.
List<ExpenseDetailsWrapper> expenseDataList = reimbursementLocalService
.getAllExpenseByReimbursementId(reimbursementId);
long fileEntryId = 0;
String previewURL = StringPool.BLANK;
List<String> billUrlData = new ArrayList<String>();
List<String> finalMerge = new ArrayList<String>();
try {
for (int i = 0; i < expenseDataList.size(); i++) {
fileEntryId = expenseDataList.get(i).getFileEntryId();
if (fileEntryId > 0) {
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId);
previewURL = DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK);
}
renderRequest.setAttribute("previewUrl", previewURL);
finalMerge.add(billUrlData);
finalMerge.add(expenseDataList);//**Error is here**The method addAll(Collection<? extends String>) in the type List<String> is not applicable for the arguments (List<ExpenseDetailsWrapper>)
LOG.info("File Entries"+fileEntryId);
}
LOG.info(billUrlData);
renderRequest.setAttribute("previewUrl", billUrlData);
renderRequest.setAttribute("expenseDataList", expenseDataList);
} catch (Exception e) {
e.printStackTrace();
}
I have one list with POJO and another one with String.. but when i am trying to add two these list into one it gives me error
Can i append two list of different type??
Yes you can with List<Object> expenseDataList but while retrieving you need to be careful and cast it.
for(Object obj : expenseDataList)
{
if(obj instanceof YourPOJO)
//take action
}

Null Pointer Exception while reading from excel? [duplicate]

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

Using Jackcess to retrieve numeric values stored in a text field gives ClassCastException

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.

Why can't I concatenate the JSON?

I need to concatenate all BasicDBObject in BasicDBList . Every time the loop runs, my BasicDBObject contains only ONE json element and exit my BasicDBList contains nothing. Why does this happen? Put the dbLinha.clear() to avoid duplicate but evaluating the code each time the loop runs BasicDBList contains a duplicate!
public BasicDBList readMetadados(Planilha planilha) {
List<String> cabecalho = new ArrayList<>();
int linhaReferencia = 0;
BasicDBObject dbLinha = new BasicDBObject();
BasicDBList listLinha = new BasicDBList();
try {
InputStream planilhaFile = new FileInputStream(FileUtils.getFile(UPLOAD_PATH, planilha.getPath()));
Sheet linhaInicial = new XSSFWorkbook(planilhaFile).getSheetAt(0);
Iterator<Row> rowIterator = linhaInicial.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
try {
if (cell.getCellType() != 3) {
if (cell.getCellType() == 1) {
if ("Veículo".equals(cell.getStringCellValue())) {
linhaReferencia = cell.getRow().getRowNum();
cabecalho.add(cell.getStringCellValue());
while (cellIterator.hasNext()) {
cabecalho.add(cellIterator.next().getStringCellValue());
}
break;
}
}
if (linhaReferencia != 0) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getCellFormula());
break;
case Cell.CELL_TYPE_BOOLEAN:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getNumericCellValue());
break;
default:
dbLinha.append(cabecalho.get(cell.getColumnIndex()), cell.getStringCellValue());
}
}
}
} catch (IllegalStateException e) {
Log.info(this, "Erro ao obter valor da linha [{}] e coluna [{}]", cell.getRow().getRowNum(), cell.getColumnIndex());
}
}
if (!dbLinha.isEmpty()) {
for(int i = 0; i < cabecalho.size(); i++){
if(!dbLinha.containsKey(cabecalho.get(i))){
dbLinha.append(cabecalho.get(i), " ");
}
}
listLinha.add(dbLinha);
dbLinha.clear();
}
}
} catch (FileNotFoundException e) {
Log.error(this, "Erro ao processar planilha: Planilha não encontrada.", e);
} catch (IOException e) {
Log.error(this, "Erro ao processar planilha.", e);
}
System.out.println(listLinha.toString());
return listLinha;
}
Output
[ { } , { } , { } , { } , { } , { }]
The content of BasicDBList the first time you run is correct, the second time is starting to duplicate and replace with added anteriormentes.
The value of BasicDBList the first time you run the loop ("if (!dbLinha.isEmpty())")
Second time
You are trying to save objects by using clear and using the same object (dbLinha) over and over again. That won't work.
When you add an object to a list, it adds a reference to that object, not a copy of that object to the list. So basically, what you add the first time is a reference to the dbLinha object, and now you have the first item in the list pointing to the same object that dbLinha is set to.
Then you call dbLinha.clear().
This means that the reference stored in your list, being the same, will now show an empty object. Then you read another line into the same object, add another reference to it to the list, and then clear it again.
Your list gets filled with references to the one, single, object that you are re-using. Here is a demonstration of what is happening:
If you want to retain your objects, you have to use new, not clear. You have to create a new object to store the next bit of data, because adding to the list does not create a copy, just a reference. So you basically have to let the reference you added point to the old object, and start with a new one.

Categories