Previously I created a login system which used a HashMap, but no database. I then ran into the problem of not being able to change the passwords of the system, as they would be reset everytime I booted up the program. It was like this:
HashMap<String, String> credentials = new HashMap<String, String>();
UserData() {
credentials.put("Manager", "adminpass");
credentials.put("Employee", "employeepass");
credentials.put("Customer", "customerpass");
}
I then realised I want to use text files to store the passwords, so I could edit them and the changes would take effect. So I created 3 text files. adminpass.txt, employeepass.txt, customerpass.txt They all contain the passwords which are 'adminpass', 'employeepass', 'customerpass' With the previous system, I used .equals to compare the password of user input and the real password as it was a string. Now it's a variable, so I am using ==. Here is my code for logging in:
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == authenticateButton) {
String roleID = usernameField.getText();
String password = String.valueOf(((JPasswordField) passwordField).getPassword());
if (credentials.containsKey(roleID)) {
if (credentials.get(roleID) == password) {
messageLabel.setForeground(Color.green);
messageLabel.setText("Login successful");
frame.dispose();
m.launch(roleID);
} else {
messageLabel.setForeground(Color.red);
messageLabel.setText("Incorrect password");
}
} else {
messageLabel.setForeground(Color.red);
messageLabel.setText("Incorrect username");
}
}
}
});
I also have read from the text files on startup, assigning what the system has read from the files to the adminpass, employeepass, and customerpass variables. Everytime I login I get 'incorrect password' even though they're correct. So I decided to do
System.out.println(credentials.get(roleID))
And it just returns null.
I'm completely confused here, I am grateful if anyone can help or point me in the right direction!
Thanks!
EDIT: when i use .equals(password)
, i get
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because the return value of "java.util.HashMap.get(Object)" is null