I'm trying to made a graphical window to add entry to a database in javafx. No problem to display the 'add entry' window, however impossible to add the entry and then refresh my database. I get a NullPointerException on getPers and CreatePerson
I tried a lot of things to initialize these variables without success. How can I do that?
Here is my class 'addPers'
public class addPers {
@FXML
private TextField nameField;
@FXML
private TextField ageField;
@FXML
private Button Cancel;
@FXML
private Button CreatePerson;
private Stage dialogStage;
private Pers pers;
private boolean okClicked = false;
private MainApp mainApp;
private PersManager persManager;
private AnchorPane databaseLayout;
private Object databaseLayoutController;
private Object rootLayout;
@FXML
private void initialize() {
}
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
public void setPers(Pers pers) {
this.pers = pers;
nameField.setText(pers.getName());
ageField.setText(Integer.toString(pers.getAge()));
}
@FXML
private void Cancel() {
dialogStage.close();
}
@FXML
public void CreatePerson(ActionEvent event) throws Exception{
// Check Form Validation;
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Please input carefully");
alert.setHeaderText(null);
if(nameField.getText().equals("")){
alert.setContentText("no valid name");
alert.showAndWait();
}
else if(ageField.getText().equals("")){
alert.setContentText("no valid age");
alert.showAndWait();
}
else{
getPers();
// Display Dialogue;
alert.setAlertType(AlertType.INFORMATION);;
alert.setContentText("Person entry created successfully");
alert.showAndWait();
}
// Change scene;
Stage stage = (Stage) CreatePerson.getScene().getWindow();
Scene scene = CreatePerson.getScene();
FXMLLoader loader = new FXMLLoader(getClass().getResource("../views/Database.fxml"));
scene.setRoot(loader.load());
stage.setScene(scene);
stage.setTitle("alt database");
stage.show();
}
public ArrayList<Pers> getPers() throws SQLException {
ArrayList<Pers> ListPers = new ArrayList<Pers>();
String query = "name, age FROM PERSONS_DB ORDER BY name;";
try {
((MainApp) this.mainApp).getDatabase().connect();
ResultSet rslt = ((MainApp) this.mainApp).getDatabase().getResultOf(query);
while (rslt.next()) {
ListPers.add(new Pers
(rslt.getString("name"),
rslt.getInt("age")
));
}
rslt.close();
try {
mainApp.showDatabaseDialog();
FXMLLoader loader = new FXMLLoader();
AnchorPane databaseEditDialog = (AnchorPane) loader.load();
DatabaseEditController controller = loader.getController();
Stage dialogStage = new Stage();
dialogStage.setTitle("database");
dialogStage.initModality(Modality.WINDOW_MODAL);
Window primaryStage = null;
dialogStage.initOwner(primaryStage);
Parent page = null;
Scene scene = new Scene(page);
dialogStage.setScene(scene);
dialogStage.show();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
}
return ListPers;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
}