NullPointerException:抛出不期望的地方

时间:2014-02-17 17:56:54

标签: java jdbc nullpointerexception

public void setSpecifications(ObservableList<Specifications> data) {
    String sql = "select * from specifications where ( bid=" + bid[0] + " or bid=" + bid[1] + " or bid=" + bid[2] + " or bid=" + bid[3] + " ) and ( mid=" + mid[0] + " or mid=" + mid[1] + " or mid=" + mid[2] + " or mid=" + mid[3] + " ) and ( vid=" + vid[0] + " or vid=" + vid[1] + " or vid=" + vid[2] + " or vid=" + vid[3] + " );";
    int colCount = 0;
    String  specVal[], paramVal = null;
    specVal = new String[]{" ", " ", " ", " "};
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        rsmd = rs.getMetaData();
        colCount = rsmd.getColumnCount();
        for (int colIndex = 0; colIndex < colCount;  colIndex++) {
            rs.beforeFirst();
            paramVal=rsmd.getColumnName(colIndex+1);
            for (int rowIndex = 0; rs.next(); rowIndex++) {
                specVal[rowIndex] = rs.getString(paramVal);
            }
            data.add(new Specifications(paramVal, specVal[0], specVal[1], specVal[2], specVal[3]));
            //**NullPointerException**
        }
    } catch (SQLException ex) {
        Logger.getLogger(Compare.class.getName()).log(Level.SEVERE, null, ex);
    }



}

堆栈追踪:

java.lang.NullPointerException
file:<path>.jar!/carshowroomsystem/details/compare/Compare.fxml
  at carshowroomsystem.dataInterface.Compare.setSpecifications(Compare.java:138)

  at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
  at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
  at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
 ...  rest of the trace

Caused by: java.lang.NullPointerException
    at carshowroomsystem.dataInterface.Compare.setSpecifications(Compare.java:138)
    at carshowroomsystem.details.compare.CompareController.addCar(CompareController.java:74)
    at carshowroomsystem.details.compare.CompareController.initialize(CompareController.java:65)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2152)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2028)
    at carshowroomsystem.WelcomeController.handleCompareAction(WelcomeController.java:106)
    ... 44 more

它在行NullPointerException投掷data.add(...),我检查了所有参数都有一些价值!不知道该怎么做。 为什么跟踪显示Compare.fxml文件?它应该是.java

1 个答案:

答案 0 :(得分:1)

您有String specVal[], paramVal = null;paramVal初始化为null。表达式paramVal=rsmd.getColumnName(colIndex+1)位于for表达式的第三部分,因此它在迭代后执行,因此第一次迭代使用null的{​​{1}}值。您需要重写代码,因为它没有意义,并了解paramVal语句如何在Java中工作。