TAGS :Viewed: 4 - Published at: a few seconds ago

[ Getting NullPointerException if i do not enter any values in my table or leave any row empty ]

 String[] header = {"Name", "Age", "Place", "Date of Birth","Qualification"};
        table_model = new DefaultTableModel(header, 3);
        table = new JTable(table_model);
        JScrollPane sp = new JScrollPane(table);

        JButton submit = new JButton("Submit");
        jp1.add(new JScrollPane(table));
        jp1.add(submit, BorderLayout.WEST);

        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {    
                try {

                    TableCellEditor editor=table.getCellEditor();

                    Connection con = DriverManager.getConnection(host, uName, uPass);
                    stmt = con.createStatement(); 

                    for(int i=0;i<table.getRowCount();i++){

                      String name = table.getValueAt(i,0).toString();
                      int age = Integer.parseInt(table.getValueAt(i,1).toString()); 
                      String place=table.getValueAt(i,2).toString();   
                      String dob=table.getValueAt(i,3).toString();
                      String qualification=table.getValueAt(i,4).toString();    
                      stmt.execute("insert into PERSONAL(NAME,AGE,PLACE,DOB,QUALIFCATION)values('"+name+"',"+age+",'"+place+"',"+dob+",'"+qualification+"')");  
                catch (SQLException ex) {   

i created a table with three rows and four columns.if i enter all values in three rows and column it will be successfully submitted.if any empty value enter in any row or column or user leaves all rows and column empty it is showing null pointer exception.But how to handle this.if user enter any null value or leaves all cells empty.it want to display a message please enter some value.after filling all values in three rows only it will allow.how to achieve thhis

Answer 1

Your table.getValueAt(i, xxxx) may return a null so calling a toString() to a null throws a runtime NullPointerException.

I suggest having a if statement to check if the value at row, column is not null, then retrieve it's toString() value.

Just guessing where the code might throw a NullPointerException.

Please debug your application to see which line of code throws the NullPointerException and fix it accordingly.