Setter method is not working when I try to pass values through different scenes in javaFX

thadaBoy :

I'm trying to pass values through setter methods between multiple scenes in java. But NullPointerException is popping up when I try to that. I want to keep the email(username) in the other controllers as well to identify the user. here is my login code.

public class Controller {

    public JFXTextField newsletterEmail;
    public JFXButton regButton;
    public JFXTextField loginUserName;
    public JFXPasswordField loginPassword;
    public JFXButton loginButton;
    Connectivity connection = new Connectivity();
    Connection connec = connection.getConnection();
    SceneSwitcher sceneSwitcher = new SceneSwitcher();
    ViewMyAccount viewMyAccount = new ViewMyAccount();

    loginValidation validateLogin = new loginValidation();

    public void loginButtonClicked(ActionEvent actionEvent) {

        System.out.println(loginUserName.getText());



        boolean validateCustomer = validateLogin.CusLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);
        boolean validateStaff = validateLogin.StaffLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);
        boolean validateOwner = validateLogin.OwnerLoginValidate(loginUserName.getText(),loginPassword.getText(),connec);

        if(loginUserName.getText().equals("") || loginPassword.getText().equals("")){
            AlertBox.displayAlertBox("ERROR!","Both fields can't be empty!");
        }else{
            if(validateCustomer){
                sceneSwitcher.switchScene(loginButton,"customerView.fxml","Customer");
            }else if(validateStaff){
                sceneSwitcher.switchScene(loginButton,"staffView.fxml","Customer");
            }else if(validateOwner){
                sceneSwitcher.switchScene(loginButton,"ownerView.fxml","Customer");
            }else{
                AlertBox.displayAlertBox("ERROR!","Invalid Username or Password! ");
            }
        }



    }

    public void registerButtonClicked(ActionEvent actionEvent) {

        sceneSwitcher.switchScene(regButton,"register.fxml","Register");
    }

    NewsletterValidation validateEmail = new NewsletterValidation();

    public void newsletterButtonClicked(ActionEvent actionEvent) throws SQLException {


        boolean isNewsletterEmailEmpty = validateEmail.invalidError(newsletterEmail);
        boolean isValid = validateEmail.isValidEmailAddress(newsletterEmail);
        boolean isEmailExist = validateEmail.checkEmailExists(newsletterEmail.getText(),connec);

        if(isNewsletterEmailEmpty && isValid && isEmailExist){

            PreparedStatement pstmt = null;
            String sql = "INSERT INTO `nwemails` (`email`)\n" +
                    "VALUES (?);";



            try {
                pstmt = connec.prepareStatement(sql);
                pstmt.setString(1,newsletterEmail.getText());

                int i = pstmt.executeUpdate();
                System.out.println("newsletter email update status = " + i);
                AlertBox.displayAlertBox("Alert!","You have successfully signed up for the news letter");


            } catch (SQLException e) {
                System.err.println(e);
            }finally {
                pstmt.close();
            }

        }else{
            System.out.println("Validation failed");
        }



    }


}

Here is my login screen:

Here is my login screen

And I want to pass the values to this controller:

public class ViewMyAccount implements Initializable {


    public Label errorPassword;
    public Label errorMobile;
    public Label errorEmail;
    public Label errorLastName;
    public Label errorFirstName;
    public TextField notes;
    public TextField address;
    public PasswordField confirmPassword;
    public PasswordField password;
    public TextField occupation;
    public TextField mobile;
    public TextField email;
    public TextField lastName;
    public TextField firstName;
    public Button updateButton;
    public Button backButton;
    Connectivity connection = new Connectivity();
    Connection connec = connection.getConnection();
    registerValidation validate = new registerValidation();
    SceneSwitcher sceneSwitcher = new SceneSwitcher();



public String mail = "[email protected]"; //I want the logged in mail to assign this  





public void initialize(URL url, ResourceBundle rb) {


            //fill info in fields
            PreparedStatement pstmtGetInfo = null;
            ResultSet rslt = null;
            String sqlGetInfo = "SELECT * FROM users WHERE email=?";
            System.out.println(mail);

            try {
                pstmtGetInfo = connec.prepareStatement(sqlGetInfo);
                pstmtGetInfo.setString(1,mail);
                rslt = pstmtGetInfo.executeQuery();

                if(rslt.next()){
                    StringBuffer stringBuffer1 = new StringBuffer();
                    stringBuffer1.append(rslt.getString("firstName"));
                    firstName.setText(stringBuffer1.toString());

                    StringBuffer stringBuffer2 = new StringBuffer();
                    stringBuffer2.append(rslt.getString("lastName"));
                    lastName.setText(stringBuffer2.toString());

                    StringBuffer stringBuffer3 = new StringBuffer();
                    stringBuffer3.append(rslt.getString("email"));
                    email.setText(stringBuffer3.toString());

                    StringBuffer stringBuffer4 = new StringBuffer();
                    stringBuffer4.append(rslt.getString("mobile"));
                    mobile.setText(stringBuffer4.toString());

                    StringBuffer stringBuffer5 = new StringBuffer();
                    stringBuffer5.append(rslt.getString("occupation"));
                    occupation.setText(stringBuffer5.toString());

                    StringBuffer stringBuffer6 = new StringBuffer();
                    stringBuffer6.append(rslt.getString("address"));
                    address.setText(stringBuffer6.toString());

                    StringBuffer stringBuffer7 = new StringBuffer();
                    stringBuffer7.append(rslt.getString("password"));
                    password.setText(stringBuffer7.toString());
                    confirmPassword.setText(stringBuffer7.toString());

                    StringBuffer stringBuffer8 = new StringBuffer();
                    stringBuffer8.append(rslt.getString("notes"));
                    notes.setText(stringBuffer8.toString());
                }else{
                    System.out.println("no rows for this mail ID");
                }




            } catch (SQLException e) {
                System.err.println(e);


            }


        }


        public void updateButtonClicked(ActionEvent actionEvent) throws SQLException{

            boolean isFirstNameEmpty = validate.emptyError(firstName,errorFirstName,"First name is required!");
            boolean isFirstNameNum = validate.isNotNum(firstName,errorFirstName,"First name can't be numbers!");
            boolean isLastNameEmpty = validate.emptyError(lastName,errorLastName,"Last name is required!");
            boolean isLastNameNum = validate.isNotNum(lastName,errorLastName,"Last name can't be numbers!");
            boolean isEmailEmpty = validate.emptyError(email,errorEmail,"Email address is required!");
            boolean isPasswordEmpty = validate.emptyError(password,errorPassword,"Password is required!");
            boolean isemailValid = validate.isValidEmailAddress(email);
            boolean isPasswordValid = validate.isValidPassword(password,confirmPassword,errorPassword);
            boolean isPasswordMatched = validate.isPasswordMatch(password,confirmPassword);
            boolean isUserNameExist = validate.checkUsernameExists(email.getText(),connec,errorEmail);




            if(isFirstNameEmpty && isFirstNameNum && isLastNameEmpty && isLastNameNum && isEmailEmpty && isPasswordEmpty && isPasswordValid && isemailValid && isPasswordMatched && isUserNameExist){
                PreparedStatement pstmt = null;
                String sql = "UPDATE users\n" +
                        "SET firstName = ?, lastName= ?, email= ?, mobile= ?, occupation= ?, address= ?, password= ?, notes= ?\n" +
                        "WHERE email = ?;";






                try {
                    pstmt = connec.prepareStatement(sql);
                    pstmt.setString(1,firstName.getText());
                    pstmt.setString(2,lastName.getText());
                    pstmt.setString(3,email.getText());
                    pstmt.setString(4,mobile.getText());
                    pstmt.setString(5,occupation.getText());
                    pstmt.setString(6,address.getText());
                    pstmt.setString(7,password.getText());
                    pstmt.setString(8,notes.getText());
                    pstmt.setString(9,mail);

                    int i = pstmt.executeUpdate();
                    System.out.println("customer info UPDATE status = " + i);

                    if(i == 1){
                        AlertBox.displayAlertBox("Congratulations!","You have successfully registered to JFS");
                        sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
                    }else{
                        AlertBox.displayAlertBox("Error","Database couldn't be updated");
                    }



                } catch (SQLException e) {
                    System.err.println(e);
                }finally {
                    pstmt.close();
                }

                AlertBox.displayAlertBox("Congratulations!","You have successfully updated your account");
                sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");

            }else{
                System.out.println("Validation failed");
            }
        }

        public void backButtonClicked(ActionEvent actionEvent) {
            sceneSwitcher.switchScene(backButton,"customerView.fxml","Welcome to JFS ");
        }




    }

I want to get the email which was input by the user in the login screen to use in this controller. Because I need that email to identify the user through process. but it shows as null. Please help me to find out what's wrong.

ViaTech :

Your issue is occurring because you are not setting the mail variable in your code before initialize is called in the ViewMyActivity controller you are attempting to pass values to.

Take my code below and create a project and test it out. This shows how to pass values between controllers in a simple, but mostly functional JavaFX FXML layout.

First loginLayout.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<GridPane fx:controller="FXMLController" 
    xmlns:fx="http://javafx.com/fxml" 
    alignment="center" 
    hgap="10" 
    vgap="10" 
    styleClass="root">

  <Text id="welcome-text" text="Login Below:" 
      GridPane.columnIndex="0" GridPane.rowIndex="0" 
      GridPane.columnSpan="2"/>

  <padding><Insets top="25" right="25" bottom="10" left="25" /></padding>

  <Label text="Username:" GridPane.columnIndex="0" GridPane.rowIndex="1" />

  <TextField fx:id="usernameField" GridPane.columnIndex="1" GridPane.rowIndex="1" />

  <Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2" />

  <PasswordField fx:id="passwordField"  GridPane.columnIndex="1" GridPane.rowIndex="2" />

  <HBox spacing="10" alignment="bottom_right" 
      GridPane.columnIndex="1" GridPane.rowIndex="4">
      <Button text="Login" 
       onAction="#handleLogin" />
  </HBox>

  <Text fx:id="usernameEntered"  GridPane.columnIndex="1" GridPane.rowIndex="6" />

</GridPane>

Now FXMLController:

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

public class FXMLController {
    ViewMyAccount viewMyAccount = new ViewMyAccount();
    @FXML private Text usernameEntered;
    @FXML private TextField usernameField;

    @FXML protected void handleLogin(ActionEvent event) {
        String enteredValue = usernameField.getText().toString();
        usernameEntered.setText("Username: " + enteredValue);

        System.out.println("From Controller: " + enteredValue);

        System.out.println("From ViewMyAccount: "+ 
                viewMyAccount.setAndReturnMail(enteredValue));

        //I cannot tell why you want to call initialize from 
        //ViewMyAccount, but this is a test showing it works
        viewMyAccount.initialize(null, null); 
    }
}

Now FXMLMain, you run this class:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class FXMLMain extends Application {

    public static void main(String[] args) {
        //you should know this but this is how you launch your application
        Application.launch(FXMLMain.class, args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("loginLayout.fxml"));

        stage.setTitle("Login");
        stage.setScene(new Scene(root, 600, 475));
        stage.show();
    }
}

Now your ViewMyAccount class, note I did comment out all of the 'pieces' that I could not run without the code:

import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;

import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.event.ActionEvent;

public class ViewMyAccount implements Initializable {

    public Label errorPassword;
    public Label errorMobile;
    public Label errorEmail;
    public Label errorLastName;
    public Label errorFirstName;
    public TextField notes;
    public TextField address;
    public PasswordField confirmPassword;
    public PasswordField password;
    public TextField occupation;
    public TextField mobile;
    public TextField email;
    public TextField lastName;
    public TextField firstName;
    public Button updateButton;
    public Button backButton;
    //I don't have this code...

    //Connectivity connection = new Connectivity();
    //Connection connec = connection.getConnection();
    //registerValidation validate = new registerValidation();
    //SceneSwitcher sceneSwitcher = new SceneSwitcher();


    public String mail = "[email protected]"; //I want the logged in mail to assign this 

    public String setAndReturnMail(String userEnteredValue) {
        this.mail = userEnteredValue;
        return this.mail;
    }

    public void initialize(URL url, ResourceBundle rb) {

            //fill info in fields
            PreparedStatement pstmtGetInfo = null;
            ResultSet rslt = null;
            String sqlGetInfo = "SELECT * FROM users WHERE email=?";
            System.out.println(mail);

            /*
            try {
                pstmtGetInfo = connec.prepareStatement(sqlGetInfo);
                pstmtGetInfo.setString(1,mail);
                rslt = pstmtGetInfo.executeQuery();

                if(rslt.next()){
                    StringBuffer stringBuffer1 = new StringBuffer();
                    stringBuffer1.append(rslt.getString("firstName"));
                    firstName.setText(stringBuffer1.toString());

                    StringBuffer stringBuffer2 = new StringBuffer();
                    stringBuffer2.append(rslt.getString("lastName"));
                    lastName.setText(stringBuffer2.toString());

                    StringBuffer stringBuffer3 = new StringBuffer();
                    stringBuffer3.append(rslt.getString("email"));
                    email.setText(stringBuffer3.toString());

                    StringBuffer stringBuffer4 = new StringBuffer();
                    stringBuffer4.append(rslt.getString("mobile"));
                    mobile.setText(stringBuffer4.toString());

                    StringBuffer stringBuffer5 = new StringBuffer();
                    stringBuffer5.append(rslt.getString("occupation"));
                    occupation.setText(stringBuffer5.toString());

                    StringBuffer stringBuffer6 = new StringBuffer();
                    stringBuffer6.append(rslt.getString("address"));
                    address.setText(stringBuffer6.toString());

                    StringBuffer stringBuffer7 = new StringBuffer();
                    stringBuffer7.append(rslt.getString("password"));
                    password.setText(stringBuffer7.toString());
                    confirmPassword.setText(stringBuffer7.toString());

                    StringBuffer stringBuffer8 = new StringBuffer();
                    stringBuffer8.append(rslt.getString("notes"));
                    notes.setText(stringBuffer8.toString());
                }else{
                    System.out.println("no rows for this mail ID");
                }

            } catch (SQLException e) {
                System.err.println(e);

            }
            */

        }


        public void updateButtonClicked(ActionEvent actionEvent) throws SQLException{

           /* boolean isFirstNameEmpty = validate.emptyError(firstName,errorFirstName,"First name is required!");
            boolean isFirstNameNum = validate.isNotNum(firstName,errorFirstName,"First name can't be numbers!");
            boolean isLastNameEmpty = validate.emptyError(lastName,errorLastName,"Last name is required!");
            boolean isLastNameNum = validate.isNotNum(lastName,errorLastName,"Last name can't be numbers!");
            boolean isEmailEmpty = validate.emptyError(email,errorEmail,"Email address is required!");
            boolean isPasswordEmpty = validate.emptyError(password,errorPassword,"Password is required!");
            boolean isemailValid = validate.isValidEmailAddress(email);
            boolean isPasswordValid = validate.isValidPassword(password,confirmPassword,errorPassword);
            boolean isPasswordMatched = validate.isPasswordMatch(password,confirmPassword);
            boolean isUserNameExist = validate.checkUsernameExists(email.getText(),connec,errorEmail);

            if(isFirstNameEmpty && isFirstNameNum && isLastNameEmpty && isLastNameNum && isEmailEmpty && isPasswordEmpty && isPasswordValid && isemailValid && isPasswordMatched && isUserNameExist){
                PreparedStatement pstmt = null;
                String sql = "UPDATE users\n" +
                        "SET firstName = ?, lastName= ?, email= ?, mobile= ?, occupation= ?, address= ?, password= ?, notes= ?\n" +
                        "WHERE email = ?;";

                try {
                    pstmt = connec.prepareStatement(sql);
                    pstmt.setString(1,firstName.getText());
                    pstmt.setString(2,lastName.getText());
                    pstmt.setString(3,email.getText());
                    pstmt.setString(4,mobile.getText());
                    pstmt.setString(5,occupation.getText());
                    pstmt.setString(6,address.getText());
                    pstmt.setString(7,password.getText());
                    pstmt.setString(8,notes.getText());
                    pstmt.setString(9,mail);

                    int i = pstmt.executeUpdate();
                    System.out.println("customer info UPDATE status = " + i);

                    if(i == 1){
                        AlertBox.displayAlertBox("Congratulations!","You have successfully registered to JFS");
                        sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");
                    }else{
                        AlertBox.displayAlertBox("Error","Database couldn't be updated");
                    }



                } catch (SQLException e) {
                    System.err.println(e);
                }finally {
                    pstmt.close();
                }

                AlertBox.displayAlertBox("Congratulations!","You have successfully updated your account");
                sceneSwitcher.switchScene(updateButton,"sample.fxml","JFS");

            }else{
                System.out.println("Validation failed");
            }

             */
        }

        public void backButtonClicked(ActionEvent actionEvent) {
           // sceneSwitcher.switchScene(backButton,"customerView.fxml","Welcome to JFS ");
        }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110293&siteId=1