0

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.

0

3 Answers 3

6

You are getting a NullPointerException thrown because you are trying to dereference (i.e. call methods on, or read fields from), a variable which is null.

In this case, it's clear that listWriters is null (because it is the only variable which is dereferenced on the line where the exception occurs - look for . characters). Since this gets assigned in your listen() method, I would guess that you get this error if you call showAll() before calling listen().

A very simple field would be to assign listWriters to an empty list in its declaration, such that it can never be null:

private List<PrintWriter> listWriters = new ArrayList<PrintWriter>();

Depending on the concurrency requirements of your application you may need to do something more elaborate, though the general principle is that you must initialise listWriters before you try to read from it.

Sign up to request clarification or add additional context in comments.

4 Comments

Or listen() and showAll() are called on different objects.
@axtavt That's a good point and a potential cause of a bug (though just a refinement, since the problem is still that listen() hasn't been called on the showAll object).
That got rid of the NullPointerException, thanks for that, but now I still can't manage to get the messages to send, even though there are no errors. Any ideas why?
@BlH It depends, what was your fix - initialising the variable in the declaration? If so, this just means it will be empty instead of null when showAll is called. The root problem is that listen() wasn't called beforehand, so no PrintWriters were added to the list. If you haven't fixed this, then you're still going to have no writers to print the msg to.
0

You must be calling showAll method before listen method. Your ListWriters is not getting initialized inside your listen method before your showAll method.

Comments

0

That may be because, you have initialized your listWriters inside listen() method.

So, if your showAll() method gets called before listen() method, it will get a null value for your listWriters (Assuming that you have declared listWriters as instance variable, and have not initialized there itself).

You can try initializing it at the place you declared it.

private List<PrintWriter> listWriters = new ArrayList<PrintWriter>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.