Java学生,试图理解为什么这个对象是Null

时间:2018-06-14 22:40:45

标签: java nullpointerexception javafx-8

请原谅我的无知,但我不明白为什么我的对象为空。我以前成功地引用了我的吸气剂。我刚刚将这个getter添加到我的initialize()方法中,它抛出了一个NullPointer异常。调试堆栈跟踪时,显示该getter不会为我的对象赋值。

我不明白为什么它有时有效,现在它不会。我刚刚创建了一个静态的最终实例,它给了我相同的null结果。我是一名完成学校项目的学生。

以下是我的CalendarControl类中引发异常的片段:

 private List<Appointment> appointments;
    static final User currentUser = LoginControl.getCurrentUser();
    //region @init
    @Override
    public void initialize(URL location, ResourceBundle resources) //from Initializable
    {
        System.out.println(currentUser.toString());
        try {
            appointments = SQLAppointmentDAO.selectAppointment(currentUser);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        for (Appointment appointment : appointments)
        {
            utilities.Timer.addAppointmentTimer(appointment);
        }

导致我出现问题的代码是

static final User currentUser = LoginControl.getCurrentUser();

这是LoginControl类的一个片段:

 private static User currentUser;

    public void login() throws IOException
    {
        String username = txtUsername.getText();
        String password = pwdPassword.getText();

        SQLUserDAO userSQL = new SQLUserDAO();

        User user;
        user = userSQL.getUserByUsername(username);

        if (user == null)
        {
            badLogon();
        }
        else if (user.verify(password))
        {
            SceneManager.getMainStage().close();
            SceneManager.getCalendarScene();
            setCurrentUser(user);
            loginLog();
        }
        else
        {
            badLogon();
        }
    }
    private void loginLog()
    {
        File loginLogFile = new File(System.getProperty("user.dir") + "/login_log.txt");
        try
        {
            loginLogFile.createNewFile();
            FileWriter writer = new FileWriter(loginLogFile, true);
            String log = getCurrentUser().getUsername() + " successfully logged in at " + LocalDateTime.now().format(
                    DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "\n";
            writer.append(log);
            writer.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static User getCurrentUser()
    {
        return currentUser;
    }

    private static void setCurrentUser(User user)
    {
        currentUser = user;
    }

0 个答案:

没有答案