0

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;
    }
  • 3
    But then you replace `userList` in the default constructor with whatever `DataLoader.loadUsers();` is returning, which I'll bet dollars to donuts is `null`. – azurefrog Apr 05 '21 at 19:19
  • Can you post your code for the `User` class that you use as well? Your user class seems to have a bunch of functions which makes it harder to pinpoint a problem given the code you have provided so far. – Daveguy Apr 05 '21 at 19:26
  • That was it @azurefrog! Thank you! – Brady Ruth Apr 05 '21 at 19:28
  • Welcome to SO. In the future, you should post the exception paying attention to the `Caused by ...` clauses which should show the file and line-number of the offending code. – Gray Apr 05 '21 at 22:04

0 Answers0