0

I am still new to Java and wondered if anyone can help me with this error? I am following a tutorial at the moment found here:

http://www.homeandlearn.co.uk/java/database_scrolling_buttons.html

I am positive i have the code exactly as it states within the action performed on the btnNext and btnFirst. But it keeps throwing an error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Employees.Workers.btnNextActionPerformed(Workers.java:167)

Can anyone see where i am going wrong?

Edit: The suggested answer does not solve this specific question. Looking at the tutorial on the site given, this code should work based on the code mentioned in this post. I need clarification on why it isn't?

The specific line throwing the error is:

(rs.next()) {

Which is below:

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

Even when removing the original local variable in DoConnect still does not allow the button to work correctly. Therefore no shadowing is occurring. Can someone please point me in the direct direction, this is exactly as the tutorial is shown.. :/

Thank you!

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Employees;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
 *
 * @author PC
 */
public class Workers extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs;

    /**
     * Creates new form Workers
     */
    public Workers() {
        initComponents();
        DoConnect();
    }

    public void DoConnect( ) {

        try {

        // Make a connection to the database
        String host = "jdbc:derby://localhost:1527/Employees";
        String uName = "user1";
        String uPass= "pass";    
        Connection con = DriverManager.getConnection( host, uName, uPass );

        //Execute SQL and load the records
        Statement stmt = con.createStatement();
        String SQL = "SELECT * FROM Workers";
        ResultSet rs = stmt.executeQuery( SQL );

        //Move the cursor to the first reocrd and get the data
        rs.next();
        int id_col = rs.getInt("ID");
        String id = Integer.toString( id_col );
        String first_name = rs.getString("First_Name");
        String last_name = rs.getString("Last_Name");
        String job = rs.getString("Job_Title");

        //Display the first record in the text field
        textID.setText(id);
        textFirstName.setText(first_name);
        textLastName.setText(last_name);
        textJobTitle.setText(job);
    }              
    catch ( SQLException err ) {
    JOptionPane.showMessageDialog(this, err.getMessage());
    }        
    }

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

        jSeparator1 = new javax.swing.JSeparator();
        textID = new javax.swing.JTextField();
        textFirstName = new javax.swing.JTextField();
        textLastName = new javax.swing.JTextField();
        textJobTitle = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnFirst = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Job Title");

        btnFirst.setText("First");
        btnFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFirstActionPerformed(evt);
            }
        });

        btnPrevious.setText("Previous");

        btnNext.setText("Next");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnLast.setText("Last");
        btnLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLastActionPerformed(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(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnFirst, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
                    .addComponent(textID, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(48, 48, 48)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(33, 33, 33)
                            .addComponent(textLastName))
                        .addComponent(textJobTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addComponent(btnNext, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(btnLast, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(77, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(textLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(textID))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textJobTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNext, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnLast, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(56, 56, 56))
        );

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

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    if (rs.next()) {
        int id_col = rs.getInt("ID");
        String id = Integer.toString( id_col );
        String first_name = rs.getString("First_Name");
        String last_name = rs.getString("Last_Name");
        String job = rs.getString("Job_Title");

        textID.setText(id);
        textFirstName.setText(first_name);
        textLastName.setText(last_name);
        textJobTitle.setText(job);
    }
    else {
        rs.previous( );
        JOptionPane.showMessageDialog(Workers.this, "End of File");
    }
    }
    catch (SQLException err) {
    JOptionPane.showMessageDialog(Workers.this, err.getMessage());
    }
    }                                       

    private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        rs.first();
        int id_col = rs.getInt("ID");
        String id = Integer.toString(id_col);
        String first_name = rs.getString("First_Name");
        String last_name = rs.getString("Last_Name");
        String job = rs.getString("Job_Title");

        textID.setText(id);
        textFirstName.setText(first_name);
        textLastName.setText(last_name);
        textJobTitle.setText(job);
    }
    catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
    }                                        

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

    /**
     * @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(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Workers.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 Workers().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField textFirstName;
    private javax.swing.JTextField textID;
    private javax.swing.JTextField textJobTitle;
    private javax.swing.JTextField textLastName;
    // End of variables declaration                   
    }
ZenoX
  • 117
  • 8
  • As was pointed out in your previous question, you are shadowing your variables. Some simple out put statements would have alerted you to this – MadProgrammer Dec 30 '15 at 00:32

1 Answers1

0

You have an instance variable ResultSet rs; defined on the class. In your DoConnect() method you are creating a new ResultSet rs variable local to that method with this:

ResultSet rs = stmt.executeQuery( SQL );

In your event method you're accessing the instance variable, which doesn't ever seem to be initialized, unless I'm missing it in your code. Therefor, it is null. Here's what you probably need to do:

public class Workers extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs; // this variable will be used in DoConnect()

    /**
     * Creates new form Workers
     */
    public Workers() {
        initComponents();
        DoConnect();
    }

    public void DoConnect( ) {

        // code omitted for brevity

        //Execute SQL and load the records
        Statement stmt = con.createStatement();
        String SQL = "SELECT * FROM Workers";
        // note here I'm setting the instance variable
        rs = stmt.executeQuery( SQL );

        // rest of code omitted for brevity.
    }
}
Gregg
  • 31,994
  • 13
  • 93
  • 189
  • I've changed ResultSet rs = stmt.executeQuery( SQL ); to this: ResultSet results = stmt.executeQuery( SQL ); and it's still giving the same error? Shall i change the original instance variable instead? Thanks! – ZenoX Dec 30 '15 at 00:37
  • I updated my answer. – Gregg Dec 30 '15 at 21:39