0

I'm wondering why it is causing a null pointer exception. I'm trying to trigger Connect() function from another class which should have connect me to the database.

MainController class:

DBConnect dbConnect;
@FXML private TextField logInField;
@FXML private PasswordField passwordField;
@FXML private Button logInButton;


@FXML private void buttonClicked() throws SQLException
{
    dbConnect.Connect();
}

@FXML private void initialize(DBConnect dbConnect)
{
    this.dbConnect=dbConnect;
}

DBConnection class:

Connection conn;
Statement st;
ResultSet rs;

public void Connect() throws SQLException
{
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookcase", "root", "1234");
    if(conn.isValid(10))
    {
        System.out.println("Connection reached");
    }
    else
    {
        System.out.println("Something went wrong!");
    }
}

It seems that the dbConnect property is not initialized, but i've already done it in initialize() method, which should be triggered after FXMLLoader loads the rest of the data, am I right? Am i using referance for the Connect() function from the other class correctly ? Regards

Mikkey
  • 35
  • 8
  • Okey, it helped. But I still dont understand, why it doesnt initialize dbConncet in initialize() function which should trigger when FXMLLoader have done his job ... – Mikkey Sep 28 '16 at 10:48
  • Most likely you are passing `null` as parameter to initialize. – 1615903 Sep 28 '16 at 10:50
  • 1
    The FXMLLoader will call the `initialize` method that has **no arguments** defined. Since your initialize method has one argument it does not get called (try it by placing a breakpoint on `this.dbConnect=dbConnect;`). Even if this method would be called what instance should the FXMLLoader pass to it? You can write a setter for `dbConnect` and you can use that setter to pass an instance. – DVarga Sep 28 '16 at 11:03
  • 1
    @Mikkey Where do you think the FXMLLoader would get the instance of `DBConnect` to pass to the `initialize()` method? What do you think the `FXMLLoader` would do if you had multiple `initialize(...)` methods with different parameters? There's just no way to make what you think/hope should work actually work. – James_D Sep 28 '16 at 11:45

0 Answers0