问题
I am getting a null pointer exception, but I dont know why. I checked to see if the cell was null before I read it to a string. So, why is that string null?
private void fillArray()
{
try
{
readBook = new HSSFWorkbook(readFile);
}
catch (IOException e)
{
System.out.println("If we know what we're doing, no one should ever see this line.");
}
if (readBook != null)
{HSSFSheet infoSheet = readBook.getSheetAt(0);
HSSFRow headingsRow = infoSheet.getRow(0);
int i = 0;
HSSFCell cell = headingsRow.getCell(i);
String columnHeading = cell.toString();
while (cell != null && !(cell.toString().equals("")))
{
cell = headingsRow.getCell(i);
columnHeading = cell.toString();
columnHeadings.add(columnHeading);
i++;
}
if(columnListIsSetup == false)
{
createList();
columnListIsSetup = true;
}
}
回答1:
I think this is the problem:
while (cell != null && !(cell.toString().equals("")))
{
// We know that cell isn't null before this line...
cell = headingsRow.getCell(i);
// ... but now we've got a new value for cell, which could be null
columnHeading = cell.toString();
columnHeadings.add(columnHeading);
i++;
}
I suspect you want to change it to:
while (cell != null && !(cell.toString().equals("")))
{
// We know cell isn't null for this...
columnHeading = cell.toString();
columnHeadings.add(columnHeading);
i++;
// It's fine to set cell to null here... we'll be
// checking again in a second...
cell = headingsRow.getCell(i);
}
回答2:
while (cell != null && !(cell.toString().equals(""))) {
cell = headingsRow.getCell(i); // here, cell gets reassigned so the
// "cell != null" check in the while
// loop condition loses it's value,
// you need to check again
if (cell == null) // add the following to make sure the NEW cell value is not null
break; //
columnHeading = cell.toString();
columnHeadings.add(columnHeading);
i++;
}
回答3:
Before making sure cell is null (or) empty, you are doing String columnHeading = cell.toString();
which could be causing the NullPointerException in case where cell is null.
来源:https://stackoverflow.com/questions/11369678/null-pointer-exception