0

I am new to Programming and I'm getting some errors when trying to create a login system using java. I'm using Netbeans to create the GUI, ask for user details, and save it in a database. But when I try to login it gives me a null pointer exception which I can't seem to resolve. Here is the programme I wrote:

public class Final_3_ClientAccountCreation extends javax.swing.JFrame {

/**
 * Creates new form ClientAccountCreation
 */
String id, fullName, contactNumber, email, district, postalCode, gender, nameWithInitials, userName, password, confirmPassword;
String accType;
Date birthDate;
Connection conn = null;
static int accNo = 211234546;

public Final_3_ClientAccountCreation() {
    initComponents();
    jTabbedPane1.setEnabledAt(1, false);
    jTabbedPane1.setEnabledAt(2, false);

}

private void switchToPersonalInfoPanel() {
    jTabbedPane1.setSelectedIndex(0);
}

private void switchToBankAccountPanel() {
    jTabbedPane1.setEnabledAt(1, true);
    jTabbedPane1.setSelectedIndex(1);
}

private void switchToOnlineAccountPanel() {
    jTabbedPane1.setEnabledAt(2, true);
    jTabbedPane1.setSelectedIndex(2);
}

private void getClientInfo() {
    this.id = regID.getText();
    this.fullName = regFullName.getText();
    this.birthDate = regBirthDate.getDate();
    this.contactNumber = regContactNumber.getText();
    this.email = regEmail.getText();
    this.district = (String) regDistrict.getSelectedItem();
    this.postalCode = regPostalCode.getText();

    if (regIsMale.isSelected()) {
        this.gender = "Male";
    } else {
        this.gender = "Female";
    }

    this.nameWithInitials = getNameWithInitials(fullName);
}

private void clearFields() {
    regBirthDate.setDate(null);
    regID.setText(null);
    regFullName.setText(null);
    regPostalCode.setText(null);
    regEmail.setText(null);
    regContactNumber.setText(null);
}

public static String getNameWithInitials(String name) {
    String nameWithInitials = "";
    String[] names = name.split("\\s+");
    String lastName = names[names.length - 1];

    for (int i = 0; i < names.length - 1; i++) {
        nameWithInitials += Character.toUpperCase(names[i].charAt(0)) + ". ";
    }

    return nameWithInitials + lastName;
}

private void setBankAccPanelValues() {
    accName.setText(nameWithInitials);
    accBirthDate.setText(birthDate + "");
    accContactNumber.setText(contactNumber);
    accDistrict.setText(district);
    accEmailAddress.setText(email);
    accPostalCode.setText(postalCode);
    regAccountNumber.setText(accNo + "");

}

private boolean verifyFields() {
    getClientInfo();

    if (id.equals("") || fullName.equals("") || birthDate.equals(null) || contactNumber.equals("") || email.equals("") || postalCode.equals("")) {
        return false;
    } else {
        return true;
    }
}

private boolean verifyUsernameandPassword() {
    userName = regUserName.getText();
    password = String.valueOf(regPassword.getPassword());
    confirmPassword = String.valueOf(regConfirmPassword.getPassword());

    if (userName.equals("") || password.equals("") || confirmPassword.equals("")) {
        JOptionPane.showMessageDialog(null, "One or More Fields are Empty", "Empty Fields", 2);
        return false;
    } else if (password.equals(confirmPassword)) {
        return true;
    } else {
        JOptionPane.showMessageDialog(null, "Passwords Don't Match!");
        return false;
    }
}

public boolean checkUsername() {
    PreparedStatement st;
    ResultSet rs;

    
    boolean usernameDoesNotExist = true;
    System.out.println("Hello");
    

    try {
        userName = regUserName.getText();
        String query = ("SELECT * FROM `users` WHERE `username` = " + userName);

        st = conn.prepareStatement(query);
        System.out.println("Hi");
        //st.setString(1, userName);
        rs = st.executeQuery();

        if (rs.next()) {
            usernameDoesNotExist = false;
            JOptionPane.showMessageDialog(null, "This Username is Already Taken, Choose Another One", "Username Failed", 2);
        }

    } catch (SQLException ex) {
        Logger.getLogger(NewUserForm.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(usernameDoesNotExist);
    return usernameDoesNotExist;
}

/**
 * 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.
 */

private void regIsMaleActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    if (regIsMale.isSelected()) {
        regIsFemale.setSelected(false);
    }
}                                         

private void regIsFemaleActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    if (regIsFemale.isSelected()) {
        regIsMale.setSelected(false);
    }
}                                           

private void BackButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    Final_2_ClientLogin newClientLoginForm = new Final_2_ClientLogin();
    newClientLoginForm.setVisible(true);
    newClientLoginForm.pack();
    newClientLoginForm.setLocationRelativeTo(null);
    this.dispose();
}                                           

private void ClearButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    clearFields();
}                                            

private void NextButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    id = regID.getText();
    fullName = regFullName.getText();
    birthDate = regBirthDate.getDate();
    contactNumber = regContactNumber.getText();
    email = regEmail.getText();
    district = (String) regDistrict.getSelectedItem();
    postalCode = regPostalCode.getText();

    if (regIsMale.isSelected()) {
        gender = "Male";
    } else {
        gender = "Female";
    }

    if (verifyFields()) {
        setBankAccPanelValues();
        switchToBankAccountPanel();
    } else {
        JOptionPane.showMessageDialog(null, "One or More Fields are Empty");
    }
}                                           

private void NextButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    switchToOnlineAccountPanel();
    this.accType = (String) regAccountType.getSelectedItem();
}                                           

private void BackButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    switchToPersonalInfoPanel();
}                                           

private void regAccountTypeItemStateChanged(java.awt.event.ItemEvent evt) {                                                
    // TODO add your handling code here:
    if (regAccountType.getSelectedIndex() == 0) {
        regFixedDepositPeriod.setEnabled(false);
    } else {
        regFixedDepositPeriod.setEnabled(true);
    }
}                                               

private void CreateAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                    
    // TODO add your handling code here:

    if (verifyUsernameandPassword()&& !checkUsername()) {
        getClientInfo();
        System.out.println("true");
        PreparedStatement ps;
        ResultSet rs;
        String registerUserQuery = "INSERT INTO `users`(`national_id`, `full_name`, `birth_date`, `contact_number`, `email`, `gender`, `district`, `postal_code`, `username`, `password`) VALUES (?,?,?,?,?,?,?,?,?,?)";

        try {

            ps = conn.prepareStatement(registerUserQuery);
            ps.setString(1, id);
            ps.setString(2, fullName);
            ps.setDate(3, (java.sql.Date) birthDate);
            ps.setString(4, contactNumber);
            ps.setString(5, email);
            ps.setString(6, gender);
            ps.setString(7, district);
            ps.setString(8, postalCode);
            ps.setString(9, userName);
            ps.setString(10, password);

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

    } else {
        System.out.println("false");
    }
}                                                   

private void BackToLoginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    // TODO add your handling code here:
    Final_2_ClientLogin newClientLoginForm = new Final_2_ClientLogin();
    newClientLoginForm.setVisible(true);
    newClientLoginForm.pack();
    newClientLoginForm.setLocationRelativeTo(null);
    this.dispose();
}                                                 

private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    System.exit(0);
}                                          

and the error I get:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at finalproject.Final_3_ClientAccountCreation.checkUsername(Final_3_ClientAccountCreation.java:143)
at finalproject.Final_3_ClientAccountCreation.CreateAccountButtonActionPerformed(Final_3_ClientAccountCreation.java:779)
at finalproject.Final_3_ClientAccountCreation$9.actionPerformed(Final_3_ClientAccountCreation.java:617)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6635)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6400)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5011)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4843)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

The error indicates that the null pointer exception is at line 143, which is in checkUsername function:

public boolean checkUsername() {
    PreparedStatement st;
    ResultSet rs;

    
    boolean usernameDoesNotExist = true;
    System.out.println("Hello");
    

    try {
        userName = regUserName.getText();
        String query = ("SELECT * FROM `users` WHERE `username` = " + userName);

        st = conn.prepareStatement(query); //this is line 143
        System.out.println("Hi");
        //st.setString(1, userName);
        rs = st.executeQuery();

        if (rs.next()) {
            usernameDoesNotExist = false;
            JOptionPane.showMessageDialog(null, "This Username is Already Taken, Choose Another One", "Username Failed", 2);
        }

    } catch (SQLException ex) {
        Logger.getLogger(NewUserForm.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(usernameDoesNotExist);
    return usernameDoesNotExist;
}

Thank you

TKBK531
  • 11
  • 3

0 Answers0