So I have a chatroom, and it used to work but I changed the code slightly to try some things out and they didn't work, so I tried to revert back to my original code but I'm not sure what I did wrong because now it is throwing a NullPointerException. My code has an ArrayList of PrintWriters and a method showAll() which does as it says; send a message to all people in the chatroom. So basically what I'm wondering is how come I am getting the exception?
//This is the main code, used to add printwriters to the arraylist and to connect to clients
//The Communicate thread is used to get input from users and use the showAll() method with that input
public void listen() {
listWriters = new ArrayList<PrintWriter>();
try {
scanner = new Scanner(System.in);
portnum = getPortNumber(scanner);
System.out.println("Listening on " + portnum);
serverSocket = new ServerSocket(portnum);
while(true) {
clientcommunicate = serverSocket.accept();
System.out.println("Connection accepted: " + clientcommunicate.toString());
PrintWriter client = new PrintWriter(clientcommunicate.getOutputStream(), true);
listWriters.add(client);
Thread t = new Thread(new Communicate(clientcommunicate));
t.start();
}
} catch (IOException ioe) {
System.err.println(ioe);
System.err.println("Error.");
System.exit(1);
}
}
//This uses a printwriter obtained in the Communicate thread; the thread initializes a socket in it with the socket obtained in the constructor
public void showAll(String msg, PrintWriter printwriter) {
for(int i = 0; i < listWriters.size(); i++) { //this is where the exception is thrown
if(!listWriters.get(i).equals(printwriter)) { //if I change the paramater listWriters.size() to a regular integer like 3, and only create 2 clients or even less, the exception is thrown here instead
listWriters.get(i).println(msg);
}
}
}
EDIT:
Ok so I'm not getting the error anymore but now I can't seem to send messages. If I send the message from my client side, there are no errors but the message doesn't show up on either client.