0

I've been trying to get a value from txt1(jtextfield) which is an id in my database. But it keep saying java.lang.NullPointerException. Here is the code:

public void harga()
{

   try {
        stat = con.createStatement();
        String query = "SELECT harga from obat WHERE ID = '"+ Integer.valueOf(txt1.getText())+"'";
        stat.executeQuery(query);
        ResultSet rs = stat.getResultSet();
        while (rs.next()) {
            int harga = rs.getInt("harga");
            //String nama = rs.getString("nama");
            System.out.println(harga);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

1

First @Sagar seems to be right as it is not ensured that there is a castable value in txt1. To ensure that you should add an ChangeListener for txt1. http://docs.oracle.com/javase/tutorial/uiswing/events/changelistener.html

Second it's bad practice to concat the query together, especially if the query parameters are coming from an UI. The reason behind this is that you are opening yourself to SQL injections. Use instead PreparedStatements: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Happy coding and welcome to Stackoverflow!

secustor
  • 3,001
  • 2
  • 14
  • 20
0

In a comment you said that txt1 is initialized as

JTextField txt1 = new JTextField();

This seems wrong: txt1 should be a variable of the class, but you wrote a local variable that doesn't exists outside that method. Try this

private JTextField txt1; //Below the class declaration "public Class ..."

txt1 = new JTextField(); //Instead of the line you wrote to initialize txt1
RaffoSorr
  • 405
  • 1
  • 5
  • 14