0

I am trying to create a search form using javaFx and MySQL. But I get an Error when I run this code.

java.lang.NullPointerException At row 55 String firstName = fname1.getText();

Maybe I missed something

Please help me.

public class FilteredEmployees implements Initializable {
      
        @FXML
        private TextField fname1; 
        @FXML
        private TableView<Employee> table;
        
        @FXML
        private TableColumn<Employee,String> fname; 
         
        String firstName = fname1.getText(); 
        String lastName = lname1.getText();
        
       public ObservableList<Employee> data = FXCollections.observableArrayList();
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
          
            try{
                String sql = "SELECT * FROM `employee` WHERE (fname LIKE '%?%') or (name LIKE '%?%')";
                Connection con = DBInfo.getConnection();
                PreparedStatement preparedStatement = (PreparedStatement)con.prepareStatement(sql);
                preparedStatement.setString(1, firstName);
                preparedStatement.setString(2, lastName);
             
                
                
                ResultSet rs = preparedStatement.executeQuery();
                
                while(rs.next()){
                
                    data.add(new Employee(rs.getInt(1), rs.getString(2), rs.getString(3), 
                            rs.getFloat(4), rs.getInt(5), rs.getString(6)));
                    
                }
                
                con.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
           
    }
Adrian
  • 13
  • 1
  • [mcve] please .. make sure the field is injected at the time you are using it – kleopatra Aug 30 '20 at 12:56
  • 5
    For simplicity, your `TextField` does not actually **exist** until the `initialize()` method is called. Furthermore, your order of code is all wrong. You're trying to get the text from the `TextField` and use it in a query before the user even has the chance to enter anything... – Zephyr Aug 30 '20 at 13:36
  • 1
    One option is to have a button that when pressed, calls a method that grabs the text inside of the `TextField` and then passes it to the `preparedStatement`. – HugoS Aug 30 '20 at 15:31

0 Answers0