I am trying to add a new instance to the Class User to an ArrayList of User. Whenever I run my program however, I keep getting a Null Pointer Exception. I've looked up similar issues on this site but it seems like most problems arise when the ArrayList is never established. However, as you can see from the code below, I establish my list at the top. Are there any other reasons this exception could be thrown when adding to the list?
import java.util.ArrayList;
public class Users {
private static Users users;
private ArrayList<User> userList = new ArrayList<User>();
private Users() {
userList = DataLoader.loadUsers();
}
public static Users getInstance() {
if (users == null) {
users = new Users();
}
return users;
}
public ArrayList<User> getUsers() {
return userList;
}
//add get user by ID
public boolean addUser(int userID, String password) {
if(haveUser(userID, password)) {
return false;
}
User user = new User(userID, password);
System.out.println(user.toString()); // I added this to make sure my parameters are being passed in correctly. They are.
userList.add(user); // This is the line where the NullPointerException is being thrown.
return true;
}
public boolean haveUser(int userID, String password) {
if (userList == null) {
return false;
}
for (User user : userList) {
if (user.getUserID() == userID && user.getPassword().equals(password)) {
return true;
}
}
return false;
}