método de selección no funciona cuando intento pasar valores a través de diferentes escenas en JavaFX

Thdbhoy:

Estoy tratando de pasar valores a través de métodos setter entre varias escenas en Java. Pero NullPointerExceptionestá apareciendo cuando trato de eso. Quiero mantener el correo electrónico (nombre de usuario) en los otros controladores también para identificar al usuario. aquí es mi código de inicio de sesión.

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");
        }



    }


}

Aquí está mi pantalla de inicio de sesión:

Aquí está mi pantalla de inicio de sesión

Y quiero pasar los valores a este controlador:

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 ");
        }




    }

Quiero conseguir el correo electrónico que fue introducido por el usuario en la pantalla de inicio de sesión para usar en este controlador. Porque necesito que el correo electrónico para identificar al usuario a través del proceso. pero muestra como nulo. Por favor, ayúdame a encontrar lo que está mal.

Viatech:

Su problema se produce porque no se está configurando el correo variable en el código antes de inicialización se llama en el ViewMyActivity controlador que está intentando pasar valores a.

Toma mi código de abajo y crear un proyecto y probarlo. Esto demuestra cómo pasar valores entre los controladores de una forma sencilla, pero sobre todo el diseño funcional JavaFX FXML.

En primer lugar 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>

Ahora 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); 
    }
}

Ahora FXMLMain , se ejecuta esta clase:

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();
    }
}

Ahora su ViewMyAccount clase, tenga en cuenta que hice comentario a cabo todas las piezas '' que no podría funcionar sin el código:

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 ");
        }

}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=221369&siteId=1
Recomendado
Clasificación