Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JavaFX connection to MySQL using a java object and controller on NetBeans

f69333d9-cc86-4a20-8c7f-d47c37ef8a53Nov 15 2014 — edited Nov 16 2014

Hi, I am developing a database application using java and javafx and I'm Using Netbeans to do so. The database that I'm using is mySQL.

I use the Scene Developer application to develop my javafx pages and put all the functions in a controller. Now the problem that I'm facing is to connect a database to the controller and then making changes to the database from the javafx screen.

I have a java class in which I establish the connection to the database and also, I have methods already defined in the same class and I use these methods to make changes in the database, Now I call these methods from the java class into the java controller for my javafx screen. Here is where I face a problem. I get a null pointer exception at the line in the controller in which I call the function from the other java class in which I had established the connection.

I have the appropriate drivers installed and everything works if I DO NOT use the javafx (i.e. it works perfectly on the netbeans gui for developing screens - I have tried it).

Can some body help me in solving this problem?

Here is the java controller for adding a Teacher to the teachers table in mysql database (I get a Null Pointer Exception at line #98):

package controllers;

import java.io.PrintWriter;

import java.io.StringWriter;

import java.net.URL;

import java.util.ResourceBundle;

import javafx.event.ActionEvent;

import javafx.fxml.FXML;

import javafx.fxml.Initializable;

import javafx.scene.Node;

import javafx.scene.control.Alert;

import javafx.scene.control.Alert.AlertType;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.RadioButton;

import javafx.scene.control.TextArea;

import javafx.scene.control.TextField;

import javafx.scene.layout.GridPane;

import javafx.scene.layout.Priority;

import javafx.scene.paint.Color;

import objects.Teacher;

import objects.TeacherQueries;

/**

*

* @author Dushyant Patel

*/

public class AddTeacherController implements Initializable {

    private Teacher currentEntry;

    private TeacherQueries teacherQueries;

    @FXML

    private TextField lastName;

    @FXML

    private TextField firstName;

    @FXML

    private TextField email;

    @FXML

    private RadioButton maleBtn;

    @FXML

    private RadioButton femaleBtn;

    @FXML

    private Button addBtn;

    @FXML

    private Button closeBtn;

    @FXML

    private Label errorMsg;

    @FXML

    private void maleButtonAction(ActionEvent event) {

        if (maleBtn.isSelected()) {

            femaleBtn.setSelected(false);

        }

    }

    @FXML

    private void femaleButtonAction(ActionEvent event) {

        if (femaleBtn.isSelected()) {

            maleBtn.setSelected(false);

        }

    }

    @FXML

    private void closeButtonAction(ActionEvent event) {

        ((Node) (event.getSource())).getScene().getWindow().hide();

    }

    @FXML

    private void addButtonAction(ActionEvent event) {

        String fname = firstName.getText();

        String lname = lastName.getText();

        String eml = email.getText();

        String gender;

        int result;

        try {

            if (!fname.equals("") && !lname.equals("") && !eml.equals("") && maleBtn.isSelected() || femaleBtn.isSelected()) {

                if (maleBtn.isSelected()) {

                    gender = "Male";

                } else {

                    gender = "Female";

                }

               

                result = teacherQueries.addTeacher(fname, lname, gender, eml);

                if (result == 1) {

                    Alert alert = new Alert(AlertType.INFORMATION);

                    alert.setTitle("Information Dialog");

                    alert.setHeaderText("Success");

                    alert.setContentText("Teacher " + fname + " " + lname + " has been added successfully!");

                    alert.showAndWait();

                } else {

                    Alert alert = new Alert(AlertType.ERROR);

                    alert.setTitle("Exception Dialog");

                    alert.setHeaderText("Failure");

                    alert.setContentText("An Exception Occured");

                    Exception ex = new Exception("AddTeacher Exception");

                    // Create expandable Exception.

                    StringWriter sw = new StringWriter();

                    PrintWriter pw = new PrintWriter(sw);

                    ex.printStackTrace(pw);

                    String exceptionText = sw.toString();

                    Label label = new Label("The exception stacktrace was:");

                    TextArea textArea = new TextArea(exceptionText);

                    textArea.setEditable(false);

                    textArea.setWrapText(true);

                    textArea.setMaxWidth(Double.MAX_VALUE);

                    textArea.setMaxHeight(Double.MAX_VALUE);

                    GridPane.setVgrow(textArea, Priority.ALWAYS);

                    GridPane.setHgrow(textArea, Priority.ALWAYS);

                    GridPane expContent = new GridPane();

                    expContent.setMaxWidth(Double.MAX_VALUE);

                    expContent.add(label, 0, 0);

                    expContent.add(textArea, 0, 1);

                    // Set expandable Exception into the dialog pane.

                    alert.getDialogPane().setExpandableContent(expContent);

                    alert.showAndWait();

                }

            } else {

                errorMsg.setText("Please fill all values");

                errorMsg.setTextFill(Color.rgb(210, 39, 30));

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    @Override

    public void initialize(URL url, ResourceBundle rb) {

        femaleBtn.setSelected(false);

        maleBtn.setSelected(false);

        errorMsg.setText(null);

    }

}

Here is the class named TeacherQueries in which the Connection to the MySQL database has been established and the methods are defined:

package objects;

/**

*

* @author Dushyant Patel

*/

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import java.util.ArrayList;

public class TeacherQueries {

    private static final String URL = "jdbc:mysql://localhost:8888/sendatabase";

    private static final String USERNAME = "root";

    private static final String PASSWORD = "1234";

    private Connection connection = null; // manages connection

    private PreparedStatement selectAllTeachers = null;

    private PreparedStatement selectTeacherByID = null;

    private PreparedStatement selectTeacherByFirstName = null;

    private PreparedStatement selectTeacherByLastName = null;

    private PreparedStatement selectTeacherByGender = null;

    private PreparedStatement selectTeacherByEmail = null;

    private PreparedStatement selectStudentByFirstAndLastNames = null;

    private PreparedStatement insertNewTeacher = null;

    private PreparedStatement updateExistingTeacher = null;

    private PreparedStatement deleteExistingTeacher = null;

    public TeacherQueries() {

        try {

            connection

                    = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            selectAllTeachers

                    = connection.prepareStatement("SELECT * FROM teachers");

            insertNewTeacher

                    = connection.prepareStatement(

                            "INSERT INTO teachers "

                            + "( firstName, lastName, gender, email ) "

                            + "VALUES ( ?, ?, ?, ?) ");

            deleteExistingTeacher

                    = connection.prepareStatement("DELETE FROM teachers WHERE id = ?");

            updateExistingTeacher

                    = connection.prepareStatement("UPDATE teachers "

                            + "SET firstName = ?, lastName = ?, gender = ?, email = ? "

                            + "WHERE id = ?");

            selectTeacherByID

                    = connection.prepareStatement("SELECT * FROM teachers WHERE id = ?");

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

            System.exit(1);

        }

    }

    public List< Teacher> getAllTeachers() {

        List< Teacher> results = null;

        ResultSet resultSet = null;

        try {

            resultSet = selectAllTeachers.executeQuery();

            results = new ArrayList< Teacher>();

            while (resultSet.next()) {

                Teacher obj = new Teacher(

                        resultSet.getInt("id"),

                        resultSet.getString("firstName"),

                        resultSet.getString("lastName"),

                        resultSet.getString("gender"),

                        resultSet.getString("email"));

                results.add(obj);

            }

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

        } finally {

            try {

                resultSet.close();

            } catch (SQLException sqlException) {

                sqlException.printStackTrace();

                close();

            }

        }

        return results;

    }

    public List< String> getTeacherNames() {

        List< String> results = null;

        ResultSet resultSet = null;

        try {

            resultSet = selectAllTeachers.executeQuery();

            results = new ArrayList< String>();

            while (resultSet.next()) {

                String fname = resultSet.getString("firstName");

                String lname = resultSet.getString("lastName");

                results.add(fname + " " + lname);

            }

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

        } finally {

            try {

                resultSet.close();

            } catch (SQLException sqlException) {

                sqlException.printStackTrace();

                close();

            }

        }

        return results;

    }

    public List< Teacher> getTeacherByID(String id) {

        List< Teacher> results = null;

        ResultSet resultSet = null;

        try {

            selectTeacherByID.setString(1, id);

            resultSet = selectTeacherByID.executeQuery();

            results = new ArrayList< Teacher>();

            while (resultSet.next()) {

                Teacher obj = new Teacher(

                        resultSet.getInt("id"),

                        resultSet.getString("firstName"),

                        resultSet.getString("lastName"),

                        resultSet.getString("gender"),

                        resultSet.getString("email"));

                results.add(obj);

            }

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

        } finally {

            try {

                resultSet.close();

            } catch (SQLException sqlException) {

                sqlException.printStackTrace();

                close();

            }

        }

        return results;

    }

    public int addTeacher(

            String fname, String lname, String gender, String email) {

        int result = 0;

        try {

            insertNewTeacher.setString(1, fname);

            insertNewTeacher.setString(2, lname);

            insertNewTeacher.setString(3, gender);

            insertNewTeacher.setString(4, email);

            result = insertNewTeacher.executeUpdate();

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

            close();

        }

        return result;

    }

    public int updateTeacher(

            String fname, String lname, String gender, String email) {

        int result = 0;

        try {

            updateExistingTeacher.setString(1, fname);

            updateExistingTeacher.setString(2, lname);

            updateExistingTeacher.setString(3, gender);

            updateExistingTeacher.setString(4, email);

            result = updateExistingTeacher.executeUpdate();

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

            close();

        }

        return result;

    }

    public int deleteTeacher(int id) {

        int result = 0;

        try {

            deleteExistingTeacher.setInt(1, id);

            result = deleteExistingTeacher.executeUpdate();

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

            close();

        }

        return result;

    }

    public void close() {

        try {

            connection.close();

        } catch (SQLException sqlException) {

            sqlException.printStackTrace();

        }

    }

}

and this is the class in which has the teacher object (it extends a super class named person). This class has the getters and setters.

package objects;

/**

*

* @author Dushyant Patel

*/

public class Teacher extends Person {

    private String email;

    public Teacher() {

        super();

    }

    public Teacher(int id, String firstName, String lastName, String gender, String email) {

        super(id, firstName, lastName, gender);

        setEmail(email);

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getEmail() {

        return email;

    }

}

Please help me someone!

Thank you!

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 13 2014
Added on Nov 15 2014
0 comments
4,341 views