0

The convertCombo() in my initialize method causes a null pointer exception, and I am not sure why. Is there any better way to convert my Objects User in the combo box so its a readable String, but still keep it as an object in the combobox so I can pass the ID from my object for later use.

public class SelectionController implements Initializable {

    @FXML
    private ComboBox<User> combobox;
    @FXML
    private Button selectButton;
    
    
    
    @Override
    public void initialize(URL arg, ResourceBundle arg2) {
        try {
            Connection conn = DBConnecter.getConnection();
            ResultSet rs = conn.createStatement().executeQuery("SELECT id,fname FROM students");
            ObservableList<User> data = FXCollections.observableArrayList();
            if(conn != null) {
                System.out.println("connected");
            }
            while(rs.next()) {
                data.add(new User(rs.getInt("id"),rs.getString("fname")));
            }
            combobox.setItems(data);
            convertCombo();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
    }
        
    public void convertCombo() {
        combobox.setConverter(new StringConverter<User>() {

            @Override
            public User fromString(String arg) {
                return null;
            }

            @Override
            public String toString(User arg) {
                return arg.getName();
            }
            
        });
    }
    
}

  • 3
    Which line is throwing the NPE? And, more importantly, do you have a [mcve] to share? – Zephyr Dec 21 '20 at 05:34
  • combobox.setItems(data); convertCombo(); The convertCombo line in the initialize statement, and I'll get back to you on the minimal reproducible example – Tony Huang Dec 21 '20 at 05:48
  • Make sure your `fx:id` and the `ComboBox` variable in the code is the same. – SedJ601 Dec 21 '20 at 06:15
  • the fx:id and the combobox variable are indeed the same. I made a simpler version that doesn't require pulling it from database and did not get the same error. That code is also quite lengthy so I'm not sure how to post that here. – Tony Huang Dec 21 '20 at 06:59
  • _That code is also quite lengthy so I'm not sure how to post that here_ not at all - distill the part that's not working into a [mcve] :) – kleopatra Dec 21 '20 at 11:57

0 Answers0