-1

I made a java program wherein an sql table will bind to a jtable. The problem is when I click row on a jtable that has blank/null data the next column of the row wouldn't display on the textfield. If the blank data is on the 4th column, the textfield would only display the data from 1st to 3rd column leaving the next textfield blank. The error that shows also is Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. I am using this sample database for this program https://www.mysqltutorial.org/wp-content/uploads/2018/03/mysqlsampledatabase.zip

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author User1
 */
public class frmCustomers extends javax.swing.JInternalFrame {

/**
 * Creates new form frmCustomers
 */
private int selectedRow;
private int totalrow;
private int row;


public frmCustomers() {
    initComponents();
    BINDDATA();
    row = 0;
    
    
    btnPrevious.setEnabled(false);
    btnFirst.setEnabled(false);
    btnNext.setEnabled(true);
    btnLast.setEnabled(true);

}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {
    pack();
}// </editor-fold>                        

private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {                                           
    BINDDATA();        
}                                          

private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
}                                        

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
    
}                                       

private void btnPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                            
    
}                                           

private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {                                        
    
}                                       

private void btnInsertActionPerformed(java.awt.event.ActionEvent evt) {                                          
    INSERT();
    BINDDATA();
}                                         

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                          
    UPDATE();  
    BINDDATA();
}                                         

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
    DELETE();
    BINDDATA();
}                                         

private void tblCustomersMouseClicked(java.awt.event.MouseEvent evt) {                                          
    DefaultTableModel table = (DefaultTableModel) tblCustomers.getModel();
    selectedRow = tblCustomers.getSelectedRow();
    
    txtCustomerNumber.setText(table.getValueAt(selectedRow, 0).toString());
    txtCustomerName.setText(table.getValueAt(selectedRow, 1).toString());
    txtContactLastName.setText(table.getValueAt(selectedRow, 2).toString());
    txtContactFirstName.setText(table.getValueAt(selectedRow, 3).toString());
    txtPhone.setText(table.getValueAt(selectedRow, 4).toString());
    txtAddressLine1.setText(table.getValueAt(selectedRow, 5).toString());
    txtAddressLine2.setText(table.getValueAt(selectedRow, 6).toString());
    txtCity.setText(table.getValueAt(selectedRow, 7).toString());
    txtState.setText(table.getValueAt(selectedRow, 8).toString());
    txtPostalCode.setText(table.getValueAt(selectedRow, 9).toString());
    jComboBox1.setSelectedItem(table.getValueAt(selectedRow, 10).toString());
    txtSalesRep.setText(table.getValueAt(selectedRow, 11).toString());
    txtCreditLimit.setText(table.getValueAt(selectedRow, 12).toString());
}                                         

public void INSERT() {
    try  {
        PreparedStatement pst;
        
        String number = txtCustomerNumber.getText().trim();
        String name = txtCustomerName.getText().trim();
        String last = txtContactLastName.getText().trim();
        String first = txtContactFirstName.getText().trim();
        String phone = txtPhone.getText().trim();
        String address1 = txtAddressLine1.getText().trim();
        String address2 = txtAddressLine2.getText().trim();
        String city = txtCity.getText().trim();
        String state = txtState.getText().trim();
        String postal = txtPostalCode.getText().trim();
        String country = (String) jComboBox1.getSelectedItem();
        String salesrep = txtSalesRep.getText().trim();
        String creditlim = txtCreditLimit.getText().trim();
        
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels",
                "root","passweird");
        
        String sql = "INSERT INTO customers values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        pst = con.prepareStatement(sql);
        pst.setString(1, number);
        pst.setString(2, name);
        pst.setString(3, last);
        pst.setString(4, first);
        pst.setString(5, phone);
        pst.setString(6, address1);
        pst.setString(7, address2);
        pst.setString(8, city);
        pst.setString(9, state);
        pst.setString(10, postal);
        pst.setString(11, country);
        pst.setString(12, salesrep);
        pst.setString(13, creditlim);
        
        pst.execute();
        
     con.close();
    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null, "Error establishing connection!!!" + e.toString());
    }    
}
private void UPDATE(){
    try {
        String number = txtCustomerNumber.getText().trim();
        String name = txtCustomerName.getText().trim();
        String last = txtContactLastName.getText().trim();
        String first = txtContactFirstName.getText().trim();
        String phone = txtPhone.getText().trim();
        String address1 = txtAddressLine1.getText().trim();
        String address2 = txtAddressLine2.getText().trim();
        String city = txtCity.getText().trim();
        String state = txtState.getText().trim();
        String postal = txtPostalCode.getText().trim();
        String country = (String) jComboBox1.getSelectedItem();
        String salesrep = txtSalesRep.getText().trim();
        String creditlim = txtCreditLimit.getText().trim();
         
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels",
                "root","passweird");
        
        Statement st = con.createStatement();
        
        String sql = "UPDATE customers set customerNumber='" + number + "', customerName='" + name
                + "', contactLastName='" + last + "', contactFirstName='" + first + "', phone='" + phone
                + "', addressLine1='" + address1 + "', adressLine2='" + address2 + "', city='" + city
                + "', state='" + state + "', postalCode='" + postal + "', country='" + country 
                + "', salesRepEmployeeNumber='" + salesrep + "', creditLimit='" + creditlim;
        
        int result = st.executeUpdate(sql);
        
        if(result > 0) {
            JOptionPane.showMessageDialog(null, "You have successfully updated the record!!!");
        }
    }
    catch (Exception e) {
    }
}
private void DELETE(){
    try{
        String number = txtCustomerNumber.getText().trim();
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels",
                "root","passweird");
        
        Statement st = con.createStatement();
        String sql = " DELETE FROM customers WHERE customerNumber = " + number;
        
        int result = st.executeUpdate(sql);
        
        if (result > 0){
            JOptionPane.showMessageDialog(null, "You have successfully deleted the record!!!");
        }
    }
        catch (Exception e){
    }
}
private void BINDDATA(){
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels",
                "root","passweird");
        
        Statement st = con.createStatement();
        String sql = "SELECT * FROM customers";
        ResultSet rs = st.executeQuery(sql);
        
        DefaultTableModel table = (DefaultTableModel) tblCustomers.getModel();
        table.setRowCount(0);
        
        while(rs.next()) {
            Object obj[] = {rs.getInt("customerNumber"), rs.getString("customerName"), rs.getString("contactLastName"), rs.getString("contactFirstName"),
                            rs.getString("phone"), rs.getString("addressLine1"), rs.getString("addressLine2"),
                            rs.getString("city"), rs.getString("state"), rs.getString("postalCode"), rs.getString("country"),
                            rs.getInt("salesRepEmployeeNumber"), rs.getObject("creditLimit"),};
                table.addRow(obj); 
                
            }
            con.close();
            
            totalrow = table.getRowCount();
        }
    catch (Exception e) {
    }
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnDisplay;
private javax.swing.JButton btnFirst;
private javax.swing.JButton btnInsert;
private javax.swing.JButton btnLast;
private javax.swing.JButton btnNext;
private javax.swing.JButton btnPrevious;
private javax.swing.JButton btnUpdate;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblCustomers;
private javax.swing.JTextField txtAddressLine1;
private javax.swing.JTextField txtAddressLine2;
private javax.swing.JTextField txtCity;
private javax.swing.JTextField txtContactFirstName;
private javax.swing.JTextField txtContactLastName;
private javax.swing.JTextField txtCreditLimit;
private javax.swing.JTextField txtCustomerName;
private javax.swing.JTextField txtCustomerNumber;
private javax.swing.JTextField txtPhone;
private javax.swing.JTextField txtPostalCode;
private javax.swing.JTextField txtSalesRep;
private javax.swing.JTextField txtState;
// End of variables declaration                   
}
eiriinjye
  • 25
  • 4
  • 1
    In your `UPDATE` method, you really shouldn't be concatenating strings to make the SQL you execute. Use a parameterised query as you do for inserting. – ndc85430 May 21 '22 at 14:34
  • 1
    `txtCustomerNumber.setText(("" + table.getValueAt(selectedRow, 0)).toString());` will probably cure your NPE but you should process nulls properly. Just see that as an emergency fix only – g00se May 21 '22 at 15:24
  • How do I process nulls properly? Sorry I'm not good at these – eiriinjye May 21 '22 at 22:58

1 Answers1

0

Check whether you're getting a null back from the database and if so, put an empty string in the relevant field in the table instead.

ndc85430
  • 1,395
  • 3
  • 11
  • 17