Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: NullPointerException when running program...

  1. #1
    Junior Member
    Join Date
    Nov 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default NullPointerException when running program...

    I am create a software app, and I am using NetBeans with MySQL as my database.

    I've created a login screen, where the user inputs user and password and has access to the main software. The user and password is saved in the MySQL database. Everytime I enter the user and password, it just throws a nullpointerexception, but the compile time is fine.

    Heres the login code: -
    package software;
     
    import java.sql.*;
    import javax.swing.*;
     
    /**
     *
     * @author RiskyShenanigan
     */
    public class Login extends javax.swing.JFrame {
     
        DatabaseConnect dc = new DatabaseConnect();
        Connection con = null;
     
     
        /** Creates new form Login */
       public Login() {
     
     
            initComponents();
        }
     
        /** 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() {
     
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jPasswordField1 = new javax.swing.JPasswordField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Aquarium Maintenance System");
            setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            setForeground(java.awt.Color.white);
            setIconImages(null);
            setResizable(false);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));
     
            jButton1.setText("OK");
            jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            jButton2.setText("Cancel");
     
            jLabel1.setText("Username:");
     
            jLabel2.setText("Password:");
     
            jPasswordField1.setHorizontalAlignment(javax.swing.JTextField.LEFT);
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(112, 112, 112)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(30, 30, 30)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2))
                            .addGap(32, 32, 32)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jPasswordField1)
                                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE))
                            .addGap(16, 16, 16)))
                    .addContainerGap(119, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(28, 28, 28)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addContainerGap(30, Short.MAX_VALUE))
            );
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(14, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String userName = jTextField1.getText();
            String password = jPasswordField1.getName();
            String passwordCheck = null;
            String userNameCheck = null;
            boolean loginFail = true;
     
              try {
                Statement st = con.createStatement();
                ResultSet rt = st.executeQuery("SELECT * " + "FROM type");
                while(rt.next()){
                   passwordCheck = rt.getString(3);
                   userNameCheck = rt.getString(2);
                   if (passwordCheck.equals(password) && userNameCheck.equals(userName)) {
                       new Menu().setVisible(true);
                       this.dispose();
                       loginFail = false;
                   }
                }
            } catch (SQLException e) {System.out.println("error login frame"); }
     
            if (loginFail == true){
                System.out.println("IncorrectLogin");
               }
     
        }                                        
     
        /**
        * @param args the command line arguments
        */
      public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                   new Login().setVisible(true);
                  }
            });
        }
     
    }

    Heres is the DatabaseConnect class: -

    package software;
     
     import java.sql.*;
     
    /**
     *
     * @author RiskyShenanigan
     */
    public class DatabaseConnect {
     
     
    public static void main(String[] args) {
    System.out.println("MySQL Connect Example");
    Connection con = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "software"; /*I created this database for me*/
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "cake";
     
    try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url+dbName,userName,password);
    System.out.println("Connected to the database");
    con.close();
    System.out.println("Disconnected from database");
    }
     
    catch (Exception e) {
    e.printStackTrace();
            }
        }
    }


  2. #2
    Member
    Join Date
    Feb 2011
    Posts
    55
    My Mood
    Tolerant
    Thanks
    1
    Thanked 16 Times in 15 Posts

    Default Re: NullPointerException when running program...

    Haven't Compiled the code, but first thing, the con variable in the Login class is never set. You have a con variable in DatabaseConnect Class, but that variable only exists inside a main method in DatabaseConnect. Essentially the DatabaseConnect Class is Empty. What you want to do is move the code in the main to the DatabaseConnect constructor, then make a getCon() method to use and assign the con variable in the Login class. Even then, I'm not sure if the sql connection is being setup correctly(lack of exp.) I hope this helps with the NullPointerException, good luck
    Last edited by JJeng; March 12th, 2011 at 12:16 AM.

  3. #3
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: NullPointerException when running program...

    I've getting a ClassNotFoundException
     
     
     import java.sql.*;
     
     
    /**
     *
     * @author RiskyShenanigan
     */
    public class DatabaseConnect {
     
      Connection con = null;
     
     public DatabaseConnect()
     {
     System.out.println("MySQL Connect Example");
     
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "software"; /*I created this database for me*/
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "cake";
     
    try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url+dbName,userName,password);
    System.out.println(con);
    System.out.println("Connected to the database");
    setConnection(con);
    con.close();
     
    System.out.println("Disconnected from database");
    }
     
    catch (Exception e) {
    e.printStackTrace();
            }
     
     }
     
    public static void main(String[] args) {
    DatabaseConnect dbc = new DatabaseConnect();
        }
     
    	 public  void setConnection(Connection con2)
    	 {
    	 con = con2;
    	 }
     
    	 public  Connection getConnection()
    	 {
    	 return con;
    	 }
    }
     

    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java: 202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.j ava:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:3 07)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launche r.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:2 48)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at DatabaseConnect.<init>(DatabaseConnect.java:25)
    at DatabaseConnect.main(DatabaseConnect.java:42)




    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
     
    /**
     *
     * @author RiskyShenanigan
     */
    public class Login extends javax.swing.JFrame {
     
     
        Connection con = new DatabaseConnect().getConnection();
        JPanel jPanel1;
    	 JTextField jTextField1;
    	 JButton jButton1, jButton2;
    	 JLabel jLabel1, jLabel2;
    	 JPasswordField jPasswordField1;
     
        /** Creates new form Login */
       public Login() {
     
     
            initComponents();
        }
     
        /** 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() {
     
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jPasswordField1 = new javax.swing.JPasswordField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Aquarium Maintenance System");
            setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            setForeground(java.awt.Color.white);
            setIconImages(null);
            setResizable(false);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));
     
            jButton1.setText("OK");
            jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            jButton2.setText("Cancel");
     
            jLabel1.setText("Username:");
     
            jLabel2.setText("Password:");
     
            jPasswordField1.setHorizontalAlignment(javax.swing.JTextField.LEFT);
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(112, 112, 112)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(30, 30, 30)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2))
                            .addGap(32, 32, 32)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jPasswordField1)
                                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE))
                            .addGap(16, 16, 16)))
                    .addContainerGap(119, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(28, 28, 28)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addContainerGap(30, Short.MAX_VALUE))
            );
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(14, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            String userName = jTextField1.getText();
            String password = jPasswordField1.getName();
            String passwordCheck = null;
            String userNameCheck = null;
            boolean loginFail = true;
     
              try {
     
    			 DatabaseConnect temp = new DatabaseConnect();
    			 con = temp.getConnection();
    			 System.out.println(con);
    			            Statement st = con.createStatement();
                ResultSet rt = st.executeQuery("SELECT * " + "FROM type");
                while(rt.next()){
                   passwordCheck = rt.getString(3);
                   userNameCheck = rt.getString(2);
                   if (passwordCheck.equals(password) && userNameCheck.equals(userName)) {
                       new JMenu().setVisible(true);
                       this.dispose();
                       loginFail = false;
                   }
                }
            } catch (SQLException e) {System.out.println("error login frame"); }
     
            if (loginFail == true){
                System.out.println("IncorrectLogin");
               }
     
        }                                        
     
        /**
        * @param args the command line arguments
        */
      public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                   new Login().setVisible(true);
                  }
            });
        }
     
    }

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: NullPointerException when running program...

    @javapenguin...
    Because maybe you don't have the driver installed?
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

Similar Threads

  1. Running out of ideas...
    By Cat in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 12th, 2011, 10:21 AM
  2. Replies: 3
    Last Post: February 23rd, 2011, 12:27 AM
  3. [SOLVED] Getting NullPointerException in program
    By jmack in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 20th, 2011, 12:48 PM
  4. Running a external exe in Mac OS
    By supertreta in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: November 15th, 2010, 12:32 PM
  5. Textpad Program Running Problems
    By Paddy in forum Java IDEs
    Replies: 4
    Last Post: January 27th, 2010, 08:14 PM