I have the following methods in my javafx application:
@FXML
private void addNewWorkerButton(ActionEvent event) {
String name = newWorkerNameTextField.getText();
int wage = Integer.parseInt(newWorkerWageTextField.getText());
allWorks.add(new Work(new Worker(getNextId(), name, wage)));
new FileHandling().writeDataToFileAsJSON(allWorks); //I save the data in JSON
setNamesChoiceBoxes();
}
}
private void setNamesChoiceBoxes() {
ArrayList<String> names = new ArrayList<>();
ArrayList<Worker> workers = new FileHandling().getWorkersDataFromJSONFile(); //I read all Workers objects from JSON
for (Worker i : workers) {
String tmp = i.getName() + " (" + i.getId() + ")";
names.add(tmp);
}
ArrayList<String> searchNames = new ArrayList<>(names);
searchNames.add(0, "All");
ObservableList<String> search = FXCollections.observableList(searchNames);
searchNameChoiceBox.setItems(search);
searchNameChoiceBox.getSelectionModel().selectFirst();
}
private void search() {
int workerID = 0;
String idString = "" + searchNameChoiceBox.getSelectionModel().getSelectedItem();
System.out.println("Search: " + searchNameChoiceBox.getSelectionModel().getSelectedItem());
if (!idString.equals("All")) {
workerID = Integer.parseInt(idString.substring(idString.indexOf("(") + 1, idString.indexOf(")")));
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
searchNameChoiceBox.setOnAction((event) -> {
search();
});
}
I have a choice box that contains all workers that my JSON file have (searchNameChoiceBox). When I add a new worker, I call the setNamesChoiceBoxes() method what reads all workers out of JSON file and refreshes the choice box. The "setOnAction" will call the search() method what gets a null here:
System.out.println("Search: " + searchNameChoiceBox.getSelectionModel().getSelectedItem());
Somehow at this line gets a "null" what should not be possible since in the setNamesChoiceBoxes() method I select the first option ("searchNameChoiceBox.getSelectionModel().selectFirst();")
Search: All // I started the application
Search: null // I added a new worker
Exception in thread "JavaFX Application Thread" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at controller.Control.search(Control.java:335) at controller.Control.lambda$4(Control.java:440) at ...
The Control.java:335 is this line:
workerID = Integer.parseInt(idString.substring(idString.indexOf("(") + 1, idString.indexOf(")")));
The Control.java:440 is the search() call in initialize() method.
I don't get a null when I work with any array.