-3

I am trying to create a login system for Java and I'm having a problem with my code. I always get this error and I don't know why.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Here is my code
 package SADlife;
import SADlife.Connection.*;
import java.sql.*;

public class loginSample extends javax.swing.JFrame {

public loginSample() {
    initComponents();
}

Connection connection = null;
Statement st;
public boolean checkLogin(){
    connection = DBConnection.getDBConnection();
    boolean check = false;
    try{
        String username = userField.getText();
        String password = passField.getText();
        String searchUser = "select username,password from userAccountsTable where username='"+username+"' and password = '"+password+"'";
        ResultSet rs = st.executeQuery(searchUser);
        while(rs.next()){
            check = true;
        }
        if (check==false){
            System.out.println("No login found!");
        }
        }catch(SQLException e){
            System.out.println(e.toString());
        }
    return check;
}



/**
 * 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() {

    userField = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    passField = new javax.swing.JPasswordField();
    loginButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    userField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            userFieldActionPerformed(evt);
        }
    });

    jLabel1.setText("Username");

    jLabel2.setText("Password");

    loginButton.setText("Submit");
    loginButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            loginButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(114, 114, 114)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(45, 45, 45))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(43, 43, 43)))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(userField, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                .addComponent(passField))
            .addContainerGap(111, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(loginButton)
            .addGap(44, 44, 44))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(112, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(userField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(29, 29, 29)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(passField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(76, 76, 76)
            .addComponent(loginButton)
            .addGap(20, 20, 20))
    );

    loginButton.getAccessibleContext().setAccessibleDescription("");

    pack();
}// </editor-fold>                        

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

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            

    if(checkLogin()){
        System.out.println("Login is correct!");
    }
    else{
        System.out.println("Wrong login!");
    }

}                                           

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(loginSample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(loginSample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(loginSample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(loginSample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new loginSample().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton loginButton;
private javax.swing.JPasswordField passField;
private javax.swing.JTextField userField;
// End of variables declaration                   

}

Here is also the the error that I'm getting

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SADlife.loginSample.checkLogin(loginSample.java:21)
at SADlife.loginSample.loginButtonActionPerformed(loginSample.java:118)
at SADlife.loginSample.access$100(loginSample.java:6)
at SADlife.loginSample$2.actionPerformed(loginSample.java:66)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Community
  • 1
  • 1
  • 3
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – David Mar 08 '16 at 15:30
  • 3
    Aside from that error, please also note that your code is wide open to SQL injection and that you're *storing user passwords in plain text*, which is ***grossly irresponsible to your users***. – David Mar 08 '16 at 15:31
  • 2
    `Statement st` is never initialized. – Neil Mar 08 '16 at 15:32
  • Please, just throw your project away. Others have done this, and much more better. Use a framework instead of creating something as easily hackable as this. – Tobb Mar 08 '16 at 15:33

1 Answers1

0

At first you should really try to fulfill the Java naming standards.

ClassName

variableName

CONSTANT

The AWT-EventQueue is a process which handles various actions on the GUI (Graphical User Interface). In your case pressing a button.

Because the Error occured in this thread it states at the beginning of the stack trace Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.

This means that a NullPointerException was thrown in the thread AWT-EventQueue-0.

The second line will show you were the problem is in your program. at SADlife.loginSample.checkLogin(loginSample.java:21)

The bold path has the following pattern

package.Class.method(File:line).

In this Case your problem is in line 21 of loginSample.java.

(Hopefully I did not mess up my counting :P) line 21 -> ResultSet rs = st.executeQuery(searchUser);

A NullPointerException is invoked if you try to apply a method on a null reference. This means that in this case st is null. So basically you never created a `Statement and saved it into your variable st.

This tutorial should help.

Best regards and good luck.

bradimus
  • 2,472
  • 1
  • 16
  • 23