Question

I am having a weird problem in this code. When I execute the code with the first if condition, it all works fine and as expected. However, when I comment that if statement and use the other if condition (the one already commented), it gives an NPE.

Both the getUserIP() and getPhoneNumber() are just normal getters for private Strings. And both values are being set before by normal setters. Why is this happening?

public void sendBroadcast(final String broadcast) {
    System.out.println("entered sendBroadcast");

        String fullPeep = broadcast;
        System.out.println("fullPeep: " + fullPeep);
        String array[] = fullPeep.split("<!!>");

        for(User tempUser: friends)
        {
            if(tempUser.getUserIP().equals(this.getUserIP()))
            {
            System.out.println("tempuser:" + tempUser.getPhoneNumber() + " user: " + array[1]);
            //if(tempUser.getPhoneNumber().equals(array[1]))
            //{
                System.out.println("tempuser:" + tempUser.getPhoneNumber() + " user: " + array[1]);
                System.out.println("if statement of broadcast method");

            try {
                DataOutputStream out2 = new DataOutputStream(socket.getOutputStream());
                out2 = tempUser.getUserDataOutputStream();
                out2.writeUTF(fullPeep + "\n");
                out2.flush();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        //}
    }
}

Exception in thread "Thread-6" java.lang.NullPointerException
at User.sendBroadcast(User.java:180)
at Server$ServerThread.run(Server.java:394)

I figured out what is causing the exception and why tempUser.getPhoneNumber() was returning null at some point.

Was it helpful?

Solution

Change:

if(tempUser.getPhoneNumber().equals(array[1]))

To:

if(java.util.Objects.equals(tempUser.getPhoneNumber(), array[1]))

Objects.equals is null-safe and will not mind when the phone number is null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top