尝试访问不为null的Java ArrayList <user>时为NullPointer

时间:2019-03-19 13:00:30

标签: java javafx arraylist nullpointerexception

我的UserController中有一个ArrayList,用于存储我的所有User实例。

我可以使用setUserList成功设置ArrayList,因为我可以循环并使用currentUser.getFirstName()打印用户的名字

我从JavaFX按钮触发了我的Login函数,并且在尝试打印以前大小为1的ArrayList并打印用户的名字时,我收到了NullPointer异常。

UserController:

 public class UserController {
    public ArrayList<User> userList;  //should contain one user thomas but gives null pointer
    //static ArrayList<User> userList;  //this does not return a null pointer

    public void setUserList(ArrayList list){
        userList = list;
        for (User user : userList) {
            User currentUser = (User) user;
            String firstName = currentUser.getFirstName();
            System.out.println("Users in the UserController: " + firstName); //prints the user thomas
        }
    }

    public void login(){
        try {
            System.out.println(userList.size()); //null pointer
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

包含登录方法的UserInterface

    public class UserInterface extends Application {

    User loggedInUser;
    UserRepo userRepo = new UserRepo();
    UserController userController = new UserController();
    Connection conn;

    //login.fxml
    @FXML
    public TextField InputEmailAddress;  
    @FXML
    public TextField InputPassword;  

    @Override
    public void start(Stage stage) throws Exception {

        String connectionURL = "jdbc:derby://localhost:1527/gymManager";
        String userName = "root";
        String userPassword= "root";
        try {

            conn = DriverManager.getConnection(connectionURL, userName, userPassword);
            if(conn != null){
                System.out.println("Connected to the database");
                ArrayList<User> list = userRepo.read(conn);

                userController.setUserList(list); //here is where I set the ArrayList<Users> in the USerController

                Parent root = FXMLLoader.load(getClass().getResource("login.fxml"));

                Scene scene = new Scene(root);

                stage.setScene(scene);
                stage.show();
            }

        } catch(SQLException e){
            System.out.println("Exception:" + e.toString()); 
        }  

    }

    public static void main(String[] args) {
        launch(args);
    }

    public void login(ActionEvent event) throws Exception{

        userController.login();

    }



}

login.fxml

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

<?import java.lang.String?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.text.Font?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1080.0" styleClass="main-pane" xmlns:fx="http://javafx.com/fxml/1" fx:controller="classmanager.UserInterface">
   <children>
      <Button fx:id="loginButton" layoutX="583.0" layoutY="451.0" onAction="#login"  mnemonicParsing="false" prefHeight="56.0" prefWidth="191.0" text="Log In">
         <font>
            <Font name="Montserrat Regular" size="13.0" />
         </font>
         <styleClass>
            <String fx:value="white-btn" />
            <String fx:value="bg-blue" />
            <String fx:value="rounded-btn" />
         </styleClass></Button>
      <Button layoutX="784.0" layoutY="451.0" mnemonicParsing="false" prefHeight="56.0" prefWidth="158.0" text="I'm new here">
         <font>
            <Font name="Montserrat Regular" size="13.0" />
         </font>
         <styleClass>
            <String fx:value="outline-btn" />
            <String fx:value="rounded-btn" />
         </styleClass></Button>
      <Button layoutX="563.0" layoutY="514.0" mnemonicParsing="false" prefHeight="38.0" prefWidth="231.0" styleClass="transparent-btn" text="I've forgotten my password">
         <font>
            <Font name="Montserrat Regular" size="13.0" />
         </font></Button>
      <Label layoutX="581.0" layoutY="273.0" prefHeight="18.0" prefWidth="411.0" text="Book classes and manage your membership details here" textFill="#9a9a9a">
         <font>
            <Font name="Montserrat Regular" size="14.0" />
         </font>
      </Label>
      <Label layoutX="577.0" layoutY="180.0" prefHeight="18.0" prefWidth="353.0" text="Welcome to the" textFill="#1a73b5">
         <font>
            <Font name="Montserrat Medium" size="30.0" />
         </font>
      </Label>
      <Label layoutX="577.0" layoutY="217.0" prefHeight="50.0" prefWidth="411.0" text="Village Hotel Gym" textFill="#1a73b5">
         <font>
            <Font name="Montserrat Medium" size="40.0" />
         </font>
      </Label>
      <ImageView fitHeight="730.0" fitWidth="544.0" layoutX="-25.0" layoutY="-4.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../login-banner.jpg" />
         </image>
      </ImageView>
      <TextField fx:id="InputEmailAddress" layoutX="581.0" layoutY="325.0" prefHeight="50.0" prefWidth="386.0" promptText="Email address" styleClass="login-input">
         <opaqueInsets>
            <Insets left="20.0" />
         </opaqueInsets>
         <font>
            <Font name="Montserrat Regular" size="13.0" />
         </font>
      </TextField>
      <TextField fx:id="InputPassword" layoutX="581.0" layoutY="384.0" prefHeight="50.0" prefWidth="386.0" promptText="Password" styleClass="login-input">
         <opaqueInsets>
            <Insets left="20.0" />
         </opaqueInsets>
         <font>
            <Font name="Montserrat Regular" size="13.0" />
         </font>
      </TextField>
   </children>
</Pane>

我简直不明白为什么UserController类中的一个方法(setUserList)会告诉我ArrayList包含1个用户,而另一个(登录)将返回NullPointer

感谢任何提示

2 个答案:

答案 0 :(得分:0)

请按以下方式更改您的用户控制器,并查看其是否有效:

public class UserController {
public ArrayList<User> userList = new ArrayList<>();  //should contain one user thomas but gives null pointer
//static ArrayList<User> userList;  //this does not return a null pointer

public void setUserList(ArrayList list){
    userList.addAll(list);
    for (User user : userList) {
        User currentUser = (User) user;
        String firstName = currentUser.getFirstName();
        System.out.println("Users in the UserController: " + firstName); //prints the user thomas
    }
}

public void login(){
    try {
        System.out.println(userList.size()); //null pointer
    } catch (Exception e) {
        System.out.println(e);
    }
}
}

答案 1 :(得分:0)

我敢打赌,另一个UserInterface实例是在fxml加载时创建的,因此那里有UserController的另一个空实例。将您的UserController用作login.fxml的控制器。

  1. fx:controller设置为UserController(我猜这些类在同一包中)。
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1080.0" styleClass="main-pane" xmlns:fx="http://javafx.com/fxml/1" fx:controller="classmanager.UserController">
  1. 将TextFields声明移至UserController
 public class UserController {
    public ArrayList<User> userList;  //should contain one user thomas but gives null pointer
    //static ArrayList<User> userList;  //this does not return a null pointer

    //login.fxml
    @FXML
    public TextField InputEmailAddress;  
    @FXML
    public TextField InputPassword;  

...
  1. 请勿在{{1​​}}中实例化userController
UserInterface
  1. 更改 public class UserInterface extends Application { User loggedInUser; UserRepo userRepo = new UserRepo(); UserController userController; Connection conn;
UserInterface#start()
  1. public void start(Stage stage) throws Exception { String connectionURL = "jdbc:derby://localhost:1527/gymManager"; String userName = "root"; String userPassword= "root"; try { conn = DriverManager.getConnection(connectionURL, userName, userPassword); if(conn != null){ System.out.println("Connected to the database"); ArrayList<User> list = userRepo.read(conn); FXMLLoader loader = new FXMLLoader(getClass().getResource("login.fxml")); Parent root = loader.load(); userController = loader.getController(); userController.setUserList(list); ... 中删除login()方法,并在UserInterface中重写login(),如下所示:
UserController