0

I have a JTextField in my form which i use for book name input. Based on this book's name, I'm trying to pass author's and publisher's values to new JFrame (NewPage) JTextFields (authortxtfield and publishertxtfield). Each time when i execute this code, i get java.lang.NullPointerException. authortxtfield and publishertxtfield are both public. Am i doing something wrong?

public void getBook(){
    try {
        ps = conn.prepareStatement("SELECT author, publisher FROM books WHERE txtfld_bookname=?");
        ps.setString(1, txtfld_bookname.getText());   
        rs = ps.executeQuery();
        while(rs.next())
        {                               
            NewPage.authortxtfield.setText(rs.getString("author"));
            NewPage.publishertxtfield.setText(rs.getString("publisher"));
        }  
    } catch(Exception e){
        JOptionPane.showMessageDialog(null,e);
    }
} 

I would also like to know if there's a way to concatenate author and publisher into one JTextField so i wouldn't have to use 2.

James A
  • 137
  • 1
  • 1
  • 11
  • Put some code that outputs each variable to the console so you can see what is NULL: System.out.println( "ps:" + ps ); Then let us know what you find. – Daniel Wisehart Sep 08 '16 at 14:44
  • Did you initialise authortxtfield and publishertxtfield with JTextField's? – BarrySW19 Sep 08 '16 at 14:48
  • @Daniel It doesn't show anything i could use: ps:com.mysql.jdbc.JDBC42PreparedStatement@9f6a9a4: SELECT author, publisher FROM books WHERE txtfld_bookname='testbook' The testbook is in the books table. – James A Sep 08 '16 at 14:57
  • @Barry I'm pretty sure NetBeans automatically initialises them once i've placed jTextFields on my form. – James A Sep 08 '16 at 14:58
  • No, that is very useful. System.out.println() will print NULL's as "null". An object reference tells you that it is not null. Keep going. You know the ps is not null. How about the rs? Or if you get an exception before the program tries to print the rs, maybe the problem is txtfld_bookname or what getText() returns. – Daniel Wisehart Sep 08 '16 at 15:01
  • @Daniel rs output rs:com.mysql.jdbc.JDBC42ResultSet@36628958 I'm pretty sure the faulty lines are these NewPage.authortxtfield.setText(rs.getString("author")); NewPage.publishertxtfield.setText(rs.getString("publisher")); – James A Sep 08 '16 at 15:08
  • 1
    It seems if i remove setText, i can output values, so my problem is in setting these values to jTextFields. – James A Sep 08 '16 at 15:18

0 Answers0