0

I am trying to query a database using a user input from a text field and display the results in a JTable. I can display all results in DB (without using a search) without error but when using a text to search I get the Null Pointer Exception.

public static void loadServiceTable(JTable tblService,String searchData,String searchField){       
    try {
        //get tblItem model
        DefaultTableModel model=(DefaultTableModel) tblService.getModel();
        //remove all rows
        model.getDataVector().removeAllElements();
        System.out.println("Rows cleared");
        //create service array from services in DB according to search
        Service[] serviceArray=ServiceController.getAllService(searchData,searchField);
        //add one row each for service in array
        System.out.println("Service array success, length = "+serviceArray.length);
        for(Service s:serviceArray){
            model.addRow(new Object[]{
                s.getServiceID(),
                //error
                s.getName(),
                s.getDetail(),
                s.getPrice(),  
            });
        }
        tblService.repaint();
        System.out.println("Repaint finished");


    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }   
    }

/*(edited) This is the output.

"After getting table model
After getting service arr, arr length = 1
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at lk.ijse.ssc.view.MainApp.loadServiceTable(MainApp.java:2800)"*/

I am using the following method for displaying all data (without a search) and it works properly.

public static void loadServiceTable(JTable tblService){       
    try {

        DefaultTableModel model=(DefaultTableModel) tblService.getModel();

        model.getDataVector().removeAllElements();

        Service[] serviceArray=ServiceController.getAllService();

        for(Service s:serviceArray){
            model.addRow(new Object[]{
                s.getServiceID(),
                s.getName(),
                s.getDetail(),
                s.getPrice(),


            });
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }   
}

The getAllService(searchData,searchField) method is given below.

public static Service[] getAllService(String searchData,String searchField) throws ClassNotFoundException, SQLException{
        //establish DB connection
        Connection con=DBConnection.getInstance().getConnection();
        //get no of services in DB and create array
        Service[] serviceArray=new Service[getRowCount(searchData,searchField)];
        //SQL statement to load matching services info from DB
        PreparedStatement pstm;


        if(searchField.equals("serviceID")) pstm=con.prepareStatement("SELECT service_id,name,detail,price FROM service WHERE service_id=?;");

        else pstm=con.prepareStatement("SELECT service_id,name,detail,price FROM service WHERE name=?;");

        pstm.setString(1,"%"+searchData+"%");
        ResultSet set=pstm.executeQuery();
        //create Item models for each record in DB and store them in Item array
        int index=0;
        while(set.next()){
            String serviceID=set.getString(1);
            String name=set.getString(2);
            String detail=set.getString(3);
            Double price=set.getDouble(4);

            serviceArray[index]=new Service(serviceID,name,detail,price);
            index++;

        }
        return serviceArray;
}

I am quite new to Java and this is my third program using Java Swing and MVC architecture. Any help is much appreciated.

  • At what line are you getting the NPE? Please [edit] your question to point it out. – Federico klez Culloca May 12 '20 at 09:42
  • Edited. I get the NPE after printing the arraylength using SOP. – Sandul Renuja May 12 '20 at 09:50
  • Looks like something in one of the elements returned by `getAllServices` is null, but it's hard to tell from your code alone. You should use a debugger to find out which element has a null field and why. – Federico klez Culloca May 12 '20 at 09:56
  • We can add null value objects to rows in JTable right? Can you tell me how I can use the debugger in Netbeans to get a detailed error log? – Sandul Renuja May 12 '20 at 09:59
  • You don't use a debugger to get a log, you use it to see the state of your variables during execution. For a start, put a breakpoint at `serviceArray[index]=new Service(serviceID,name,detail,price);` in `getAllServices` and see what values are getting put inside the array. – Federico klez Culloca May 12 '20 at 10:03
  • Thanks. The error is in the ResultSet object, while(set.next()) is not getting executed. – Sandul Renuja May 12 '20 at 10:28

0 Answers0