Search code examples
javanullpointerexceptionobjectinputstreamobjectoutputstream

NullPointer exception when adding ObjectInputStream to a HashMap


I'm trying to write a basic chat server which will forward messages from one client to another.

I have my client running on another laptop and the server gets the user name which I send so surely the ObjectInputStream isn't null and the user name isn't null?

Here is the HashMap and ObjectInputStream:

private Socket[] clientSocket = new Socket[100];
private ObjectInputStream[] fromClient = new ObjectInputStream[100];
private ObjectOutputStream[] toClient = new ObjectOutputStream[100];
private HashMap<String, ObjectInputStream> clientInputs= new HashMap<String, ObjectInputStream>();
private HashMap<String, ObjectOutputStream> clientOutputs= new HashMap<String, ObjectOutputStream>();;

Here's the bit where I get the null pointer exception:

//This is just for testing:
System.out.println("User name is :" +userName);
System.out.println("fromClient[i] is " +fromClient[i].toString());
Thread.sleep(1000);

//Add this user to all lists.
clientInputs.put(userName , (ObjectInputStream)fromClient[i]);*
clientOutputs.put(userName, (ObjectOutputStream)toClient[i]);
onlineUsers[i] = userName;

I get: [Line 105 is the line clientInputs.put(...,...); where I marked with a *.]

    User name is :hulo
    fromClient[i] is java.io.ObjectInputStream@147c5fc
    Exception in thread "Thread-0" java.lang.NullPointerException
        at AcceptConnections.addNextUser(AcceptConnections.java:105)
        at AcceptConnections.run(AcceptConnections.java:53)

I don't know if this has anything to do with it but without the line Thread.sleep(1000); the NullPointerException comes out after the "user name is" line but before the "fromClient[i]" line.

Edit: I'm not sure if I made it clear, but these lines of code are after my client program has connected to the server so the user name is the one taken from the client during a test run and so the ObjectInputStream is definitely working.


Solution

  • It looks like you're not initializing clientInputs.

    Maybe change your declaration to:

    private HashMap clientInputs= new HashMap();