Results 1 to 13 of 13
  1. #1
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default GUI and NullPointerException

    Hello. I'm working on a project that uses a GUI to show and manipulate entries in a database. The code compiles and runs, and the GUI correctly shows the first entry in the database. I then added a JButton to the GUI so the user can advance to the next entry in the database, and wrote the code for the "Next" button. The program compiles and runs, and the GUI correctly shows the first entry in the database. But when I click on the "Next" button, I get a NullPointerException. Can anyone help me fix this?

    The code to show the first entry in the database:
    Java Code:
    package Employees;
    // This program builds a GUI to access and manipulate the "Employess" database
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import javax.swing.JOptionPane;
    
    public class Workers extends javax.swing.JFrame {
        Connection con;
        ResultSet rs;
        Statement stmt;
    
        public Workers() {
            initComponents();
            DoConnect();     
        }
        
        public void DoConnect() {
            try {
                // Connecting to the database
                String host = "jdbc:derby://localhost:1527/Employees";
                String uName = "admin";
                String pWord = "admin";
                Connection con = DriverManager.getConnection(host, uName, pWord);
                
                // Query SQL and load results into ResultSet
                Statement stmt = con.createStatement();
                String SQL = "SELECT * FROM APP.Workers";   
                ResultSet rs = stmt.executeQuery(SQL);
                
                // Getting the data from the database
                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 recod in the GUI
                textID.setText(id);
                textFName.setText(first_name);
                textLName.setText(last_name);
                textJob.setText(job);
                
            }        
            catch (SQLException err) {
                JOptionPane.showMessageDialog(Workers.this, err.getMessage());
                
            }
        }
    The code to show the "Next" entry in the database. The NullPointerException points to the first line of the "try" block: if (rs.next()) {

    Java Code:
    private void butNextActionPerformed(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);
                    textFName.setText(first_name);
                    textLName.setText(last_name);
                    textJob.setText(job);
                    
                }
                else {
                    rs.previous();
                    JOptionPane.showMessageDialog(Workers.this, "No More Records in File");
                    
                }        
            }     
            
            catch (SQLException err) {
                JOptionPane.showMessageDialog(Workers.this, err.getMessage());
            }  
        
        }
    Thanks for your help.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: GUI and NullPointerException

    A NullPointerException occurs when you use an expression as if it had a nonnull value when it is really null. Arrays and method calls are common places for this to happen, and the thing which is null can be a variable or a more complex expression.

    Java Code:
    String[] arr;
    System.out.println(arr[0]); // bad! arr is null
    arr = new String[42];
    System.out.println(arr[0]); //ok
    System.out.println(arr[0].length()); // bad! arr[0] is null
    Your case is comparatively simple:

    Java Code:
    rs.next()
    There's only one thing that can possibly be null here: and that's rs. (If the NullPointerExpression occurs somewhere within next() instead, the compiler will say that.) We can easily check that using System.out.println().

    Java Code:
    try {
        System.out.println("About to call next() in the button handler, rs=" + rs);
        if ( rs.next() ){
            int id_col = rs.getInt("ID");
            // etc
    Once you have verified that rs is the culprit here (that it is null) then you have to go back through your code to where you thought you had given rs a nonnull value and figure out why that didn't happen.

    [Edit] More generally, it might be the case that you gave rs a nonnull value and it became null later. But this is not the case here - you assign a value to a ResultSet variable exactly once. Variables in Java don't just become null, you have to assign null to them. Evidently that assignment to a ResultSet variable did not do what you thought it did.
    Last edited by pbrockway2; 10-11-2012 at 11:05 PM.

  3. #3
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: GUI and NullPointerException

    Hello. Thanks for your reply.

    Sorry: line 2 in your second eample looks like it was cut off (at least on my screen).
    System.out.println("About to call next() in the button handler, rs = " + (this part is missing))

    I'm guessing the missing part is rs.next(), which if I understand correctly should return either true or false.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: GUI and NullPointerException

    [Edit] Ignore what was here.

    The line should say

    Java Code:
    System.out.println(
            "About to call next() in the button handler, rs=" 
            + rs);
    What I'm thinking you'll see is a message "About to call next() in the button handler, rs=null".
    Last edited by pbrockway2; 10-11-2012 at 11:17 PM.

  5. #5
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: GUI and NullPointerException

    Hello. So I tried this:
    [CODE]
    private void butNextActionPerformed(java.awt.event.ActionEvent evt) {

    try {
    System.out.println("trying Next button: rs = " + rs);
    if ( rs.next() ){
    int id_col = rs.getInt("ID");
    String id = Integer.toString(id_col);
    //etc
    [\CODE]

    The program dutifully compiles, runs, and correctly shows the first entry in the database. When I click the next button, the system prints out "trying Next button rs = null", and then the npe error messages.

    So, I have only used rs in three lines of code (see initial post): line 12, line 34, and then in the if (rs.nest()) { line. I have no idea how rs then gets set to null. Yes, I am using NetBeans, so I left out the parts of the code that NetBeans creats automatically. I will look through that code to see if there are any references to rs there.

    Thanks for your help.

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: GUI and NullPointerException

    As I suggested it is assignments to rs that matter. You say things like rs.getInt("ID"), but there's no way that calling the nextInt() is going to make rs null.

    The only assignment occurs where you say:

    Java Code:
    ResultSet rs = stmt.executeQuery(SQL);
    You can System.out.println(rs) at this point and see that it has a perfectly good, nonnull value. As mentioned before, there is nothing in the code that assigns any different value. Yet rs is null in the event handler as you've found.

    There can only be one way out of the paradox: the rs variable you give a nonnull value to in DoConnect() is not the same variable as the rs variable you use in the button handler. If that's not enough of a hint, remember that you get a new variable each and every time you declare one. And a declaration is a thing that gives the variable and its type.

  7. #7
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: GUI and NullPointerException

    Hello. I appreciate the help, and I confess I'm still not getting it.

    As you say, after the line rs = stmt.executeQuery(SQL), I can get the system to tell me rs = jdbc derby client localhost etc.
    And after the try { if (rs.next()) { line, the system tells me rs = null

    (I am learning some useful tips on tracking down problems!!)

    I notice the Next button ActionPerformed is private, so I tried to re-assign rs, like so:

    Java Code:
    private void butNextActionPerformed(java.awt.event.ActionEvent evt) {
                    
            try {
                Statement stmt = con.createStatement();
                String SQL = "SELECT * FROM APP.Workers";   
                ResultSet rs = stmt.executeQuery(SQL);
                
                System.out.println("rs3 = " + rs);
                
                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);
                    textFName.setText(first_name);
                    textLName.setText(last_name);
                    textJob.setText(job);
                    
                }
                else {
                    rs.previous();
                    JOptionPane.showMessageDialog(Workers.this, "No more records in file");
                    
                }        
            }     
            
            catch (SQLException err) {
                JOptionPane.showMessageDialog(Workers.this, err.getMessage());
            }  
        
        }
    The code compiles, runs, the GUI correctly displays the first entry in the database, and when I click the next buton, I get npe, this time referencing the line Statement stmt = con.createStatement();

    Can I get another hint? Sorry to be so obtuse.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: GUI and NullPointerException

    There's only one variable on that line that can cause a NPE, con. Have you tested if it's null before using it? Where do you create it?

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: GUI and NullPointerException

    Ah, you're shadowing a variable. For instance:

    Java Code:
    class Foo {
       private Bar bar; // Line (A)
    
       public Foo() {
          Bar bar = new Bar(); // Line (B)
       }
    
       public void someMethod() {
          bar.someBarMethod();  // Line (C)
       }
    The code above will cause a NPE to occur at line (C). The reason is because even though you declare your Bar variable, bar, in the class at line (A), you re-declare it in the constructor and create it there on line (B). This re-declared bar is local to the constructor, doesn't exist outside of the block it was declared in, and has no effect on the bar variable declared at line (A). The solution is not to re-declare bar locally, to instead use the class variable:

    Java Code:
    class Foo {
       private Bar bar; // Line (A)
    
       public Foo() {
          // Bar bar = new Bar(); // Line (B-1)
          bar = new Bar(); // Line (B-2)
       }
    
       public void someMethod() {
          bar.someBarMethod();  // Line (C)
       }
    Now (C) will not throw a NPE.

  10. #10
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: GUI and NullPointerException

    Hello. thanks for your response.

    Bu..bu..but..

    In my inital post (above) I presented some code that did not have this kind of variable shadowing (as far as I understand it), yet the program was giving me NPE only when I clicked on the Next button in the GUI. If I understand pbrockway2 correctly, s/he was suggesting that the rs variable in DoConnect() is different from the rs variable in butNextActionPerformed().

    So I changed the code as a clumsy way to force rs to be assigned as it is in DoConnect(). Anyways, it doesn't work.

    I appreciate any ideas you have to fix this. thanks.

  11. #11
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: GUI and NullPointerException

    In your original DoConnect() you were also shadowing rs.

    You declared it as part of the class near the start, then you declared another rs in DoConnect(). The first (class) declaration is the good one because you want to use this variable in two methodz. Remove the declaration in DoConnect().

  12. #12
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: GUI and NullPointerException

    Hello. Eureka - not only does it work, but I understand better the entire issue of rs variable being assinged at one point but null at another! As usual, the cause of 98% of my problems can be found between my ears.

    Thank you so much.

    OK now, I'm going to build the "First", "Back", and "Last" buttons to move around in the database. yippee

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: GUI and NullPointerException

    You're welcome. It's worth the pain once, to really see what's going on.

    Good luck with the rest of the program.

Similar Threads

  1. NullPointerException
    By mangesh.gho in forum New To Java
    Replies: 11
    Last Post: 01-21-2012, 07:19 AM
  2. nullpointerexception
    By natdizzle in forum New To Java
    Replies: 3
    Last Post: 01-14-2012, 10:57 PM
  3. NullPointerException
    By Diz in forum New To Java
    Replies: 10
    Last Post: 05-13-2011, 03:58 AM
  4. NullPointerException
    By donchini in forum New To Java
    Replies: 4
    Last Post: 05-20-2010, 02:11 AM
  5. NullPointerException
    By tommyyyy in forum New To Java
    Replies: 9
    Last Post: 03-26-2009, 11:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •