Input/Output NullPointerException, aber wieso? [Apache POI]

fabipfolix

Mitglied
Ich versuche hier die 4. und 5. Cell einer Row der Apache POI auszulesen, allerdings bekomme ich immer eine NullPointerException:
at application.DBReader.readSheet1(DBReader.java:90)
at application.Main.start(Main.java:19)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/678208545.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/410424423.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/471405867.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/1963387170.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/237061348.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Allerdings verstehe ich nicht wieso das passiert, hier der Code:
Java:
            if(row!=null) {
                System.out.println("row!=null");
            }
            if(row.getLastCellNum()-1>=5) { //ERROR: java.lang.NullPointerException
                System.out.println("in if"); //wird nicht ausgeführt
                sDA =  row.getCell(4).getDateCellValue();
                System.out.println(sDA);
            }
Java:
package application;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;




public class DBReader {
    List<Mini> miniList = new ArrayList<Mini>();
  
    public List<Mini> readSheet1() throws FileNotFoundException, IOException{
      
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("DB.xls"));
      
        HSSFSheet sheet = wb.getSheetAt(0);
        for(int i=0;i<=sheet.getLastRowNum();i++) {
            String name = "error";
            double age = 4;
            int max=10;
            Date sDA;
            Date sDE;
          
         
            Row row = sheet.getRow(i);
            if(row ==null) {
                System.out.println("row=null");
                continue;
            }
          
            Cell c = row.getCell(0);
            c.setCellType(CellType.STRING);
          
          
          
            if(c.getCellTypeEnum()==CellType.STRING) { //NAME
              
                name = row.getCell(0).getStringCellValue();
              
            } else {
                System.out.println("Zeichenkette benötigt");
            }
          
            if(row.getCell(1).getCellTypeEnum()==CellType.NUMERIC) { //BirthYear
                age = row.getCell(1).getNumericCellValue();
              
            } else {
                System.out.println("nur Zahlen erlaubt");
            }
          
            if(row.getCell(2).getCellTypeEnum()==CellType.NUMERIC) { //MaxMini
                max = (int) row.getCell(2).getNumericCellValue();
              
            } else {
                System.out.println("nur Zahlen erlaubt");
            }
          
            if(row!=null) {
                System.out.println("row!=null");
            }
            if(row.getLastCellNum()-1>=5) { //ERROR: java.lang.NullPointerException
                System.out.println("in if"); //wird nicht ausgeführt
                sDA =  row.getCell(4).getDateCellValue();
                System.out.println(sDA);
            }
              
          
          
          
          
            Mini m = new Mini(name, age,max);
            miniList.add(m);
          
        }
    wb.close();
    return miniList;
      
    }
  
    public void writeMiniList(List<Mini> lM) throws FileNotFoundException, IOException {
      
        HSSFWorkbook wb = new HSSFWorkbook();
      
        HSSFSheet sheet = wb.createSheet("Main");
      
      
      
      
        for(int i=0;i<=lM.size()-1;i++) { //
            String n = lM.get(i).getName();
            int b = lM.get(i).getBirthYear();
            int mM =lM.get(i).getMaxMini();
          
            if(sheet.getRow(i)==null) {
                HSSFRow row = sheet.createRow(i);
                HSSFCell name = row.createCell(0);
                HSSFCell birthYear = row.createCell(1);
                HSSFCell maxMini = row.createCell(2);
              
                name.setCellValue(n);
                birthYear.setCellValue(b);
                maxMini.setCellValue(mM);
            } else {
                HSSFRow row = sheet.getRow(i);
                HSSFCell name = row.getCell(0);
                HSSFCell birthYear = row.getCell(1);
                HSSFCell maxMini = row.getCell(2);
              
                name.setCellValue(n);
                birthYear.setCellValue(b);
                maxMini.setCellValue(mM);
            }
      
        }
      
        try {
          
            wb.write(new FileOutputStream("DB.xls"));
            System.out.println("File updated");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        try {
            wb.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
    }
    public LocalDate convertDateToLocalDate(Date dateToConvert) {
        return dateToConvert.toInstant()
          .atZone(ZoneId.systemDefault())
          .toLocalDate();
    }
  
}
 
Naja, wenn row null ist läufst du ja trotzdem in den Code mit dem getLastCellNum() Aufruf hinein. Vermutlich wurde auch nicht ausgegeben "row!=null".
 
Poste bitte mal die korrekte Klasse DBReader mit dem korrekten Stacktrace. In dem von dir geposteten Codeschnipsel der Klasse DBReader zeigt Zeile 90 auf eine ungültige Codezeile.
Und ganz sicher ist row null, wenn es sich wirklich um diese Zeile handelt, in der die Exception geworfen wird.
Benutze einfach einen Debugger, und gucke, ob row dort null ist.
 
Poste bitte mal die korrekte Klasse DBReader mit dem korrekten Stacktrace. In dem von dir geposteten Codeschnipsel der Klasse DBReader zeigt Zeile 90 auf eine ungültige Codezeile.
Und ganz sicher ist row null, wenn es sich wirklich um diese Zeile handelt, in der die Exception geworfen wird.
Benutze einfach einen Debugger, und gucke, ob row dort null ist.
Im Spoiler ist die ganze Klasse DBReader und Zeile 90 hat doch gar keinen Inhalt 😱

Das mit dem Debugger könnte ein Weilchen dauern, keine Ahnung wie das funktioniert ^^
 
Ups, ich hatte Leerzeilen gelöscht
Java:
package application;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;




public class DBReader {
    List<Mini> miniList = new ArrayList<Mini>();
 
    public List<Mini> readSheet1() throws FileNotFoundException, IOException{
     
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("DB.xls"));
     
        HSSFSheet sheet = wb.getSheetAt(0);
        for(int i=0;i<=sheet.getLastRowNum();i++) {
            String name = "error";
            double age = 4;
            int max=10;
            Date sDA;
            Date sDE;
         
        
            Row row = sheet.getRow(i);
            if(row ==null) {
                System.out.println("row=null");
                continue;
            }
         
            Cell c = row.getCell(0);
            c.setCellType(CellType.STRING);
         
         
         
            if(c.getCellTypeEnum()==CellType.STRING) { //NAME
             
                name = row.getCell(0).getStringCellValue();
             
            } else {
                System.out.println("Zeichenkette benötigt");
            }
         
            if(row.getCell(1).getCellTypeEnum()==CellType.NUMERIC) { //BirthYear
                age = row.getCell(1).getNumericCellValue();
             
            } else {
                System.out.println("nur Zahlen erlaubt");
            }
         
            if(row.getCell(2).getCellTypeEnum()==CellType.NUMERIC) { //MaxMini
                max = (int) row.getCell(2).getNumericCellValue();
             
            } else {
                System.out.println("nur Zahlen erlaubt");
            }
         
            if(row!=null) {
                System.out.println("row!=null");
            }
            if(row.getLastCellNum()-1>=5) { //ERROR: java.lang.NullPointerException
                System.out.println("in if"); //wird nicht ausgeführt
                sDA =  row.getCell(4).getDateCellValue();
                System.out.println(sDA);
            }
             
         
         
         
         
            Mini m = new Mini(name, age,max);
            miniList.add(m);
         
        }
    wb.close();
    return miniList;
     
    }
 
    public void writeMiniList(List<Mini> lM) throws FileNotFoundException, IOException {
     
        HSSFWorkbook wb = new HSSFWorkbook();
     
        HSSFSheet sheet = wb.createSheet("Main");
     
     
     
     
        for(int i=0;i<=lM.size()-1;i++) { //
            String n = lM.get(i).getName();
            int b = lM.get(i).getBirthYear();
            int mM =lM.get(i).getMaxMini();
         
            if(sheet.getRow(i)==null) {
                HSSFRow row = sheet.createRow(i);
                HSSFCell name = row.createCell(0);
                HSSFCell birthYear = row.createCell(1);
                HSSFCell maxMini = row.createCell(2);
             
                name.setCellValue(n);
                birthYear.setCellValue(b);
                maxMini.setCellValue(mM);
            } else {
                HSSFRow row = sheet.getRow(i);
                HSSFCell name = row.getCell(0);
                HSSFCell birthYear = row.getCell(1);
                HSSFCell maxMini = row.getCell(2);
             
                name.setCellValue(n);
                birthYear.setCellValue(b);
                maxMini.setCellValue(mM);
            }
     
        }
     
        try {
         
            wb.write(new FileOutputStream("DB.xls"));
            System.out.println("File updated");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     
        try {
            wb.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     
    }
    public LocalDate convertDateToLocalDate(Date dateToConvert) {
        return dateToConvert.toInstant()
          .atZone(ZoneId.systemDefault())
          .toLocalDate();
    }
 
}


wb.close() ist also das Problem.
 
Auch jetzt zeigt Zeile 90 immer noch nicht auf eine gültige Codezeile. Und wb.close() ist ganz sicher nicht das Problem. Wenn wb null wäre, würde es schon viel früher knallen bei wb.getSheetAt(0);.
 
Java:
for(int i=0;i<=sheet.getLastRowNum();i++)
Sicher, dass du hier <= schreiben wolltest? Laut Doku ist getRow(int) doch 0-based.
 
<= ist richtig. getLastRowNum() liefert ja nicht die Anzahl der Zeilen, sondern den tatsächlichen Index der letzten Zeile. Wenn das Sheet also nur eine einzige Zeile hat, ist getLastRowNum() == 0.
 
Allerdings hat meine Datei mindestens 3 Zellen pro Reihe
EDIT: ah hab mich wohl verlesen. Ich schaus mir später nochmal an, habe gerade keine Zeit mehr.
 

Zurück
Oben