NullPointerException

im reading Head first java, and im programming a chat client from the book but its not working when ever i run my program i get this error

java.lang.NullPointerException

at userChat$IncomingReader.run(userChat.java:81)

at java.lang.Thread.run(Thread.java:619)

here is the portion of code it says is jacked up

publicvoid run()

{

String message;

try

{

while((message = reader.readLine()) !=null)

{

System.out.println("read" + message);

incoming.append(message +"\n");

}

}

catch(Exception ex)

{

System.out.println("Error: " + ex);

ex.printStackTrace();

}

}

while((message = reader.readLine()) != null) is line 80 and if anyone has the book its on page 519.

So does anyone know how i can fix this?

[1324 byte] By [The_Undeada] at [2007-11-27 11:52:33]
# 1

while((message = reader.readLine()) != null)

If this line is throwing a NPE the most likely cause is that reader has not been initialised.

floundera at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 2

thanx for the reply.but no it was initilized

private void setUpNetworking()

{

try

{

sock = new Socket(ip, 6928);

InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());

reader = new BufferedReader(streamReader);

writer = new PrintWriter(sock.getOutputStream());

System.out.println("Networking Established");

}

catch(Exception e)

{

//System.out.print("Error: " + e);

e.printStackTrace();

}

}

if you need i could post the rest of my code if that would help

Message was edited by:

The_Undead

The_Undeada at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 3

Your code can give a compilation failure error like NullPointerException what you are trying to do is to use a String object 'message' before instantiating it with a value. Obviously when u only declare a variable or object and dont initialize it, that takes a default value. Here in your code the message is declared of type String but it is not assigned a value, hence it takes the default value that is null (in case of String). But you cannot fiddle with it or use it until it holds / u assign a value to it. In ur code you are actually using it , so a NullPointerException error is thrown in such cases. !

aron_phila at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 4

System.out.println(reader);

System.out.println(reader.ready());

Try adding this before your while loop.

floundera at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 5

it comes out has null, oh and i rally appreciate your helping me

The_Undeada at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 6

I guess its the 'message' thats needed to be initialized but not the reader !

aron_phila at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 7

> I guess its the 'message' thats needed to be

> initialized but not the reader !

I dont think so

The_Undeada at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 8

TO FLOUNDER:

Could you please explain what was the correction and how ur snippet actually works for this code ? Kindly provide a clear layman explanation if possible ! Was my reasoning and explanation also right ?

I actually dint follow the logic/ reason in ur snippet and how it would help come out of NPE !

Thanks in advance !

aron_phila at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 9

> TO FLOUNDER:

>

> Could you please explain what was the correction and

> how ur snippet actually works for this code ? Kindly

> provide a clear layman explanation if possible ! Was

> my reasoning and explanation also right ?

>

> I actually dint follow the logic/ reason in ur

> snippet and how it would help come out of NPE !

>

> Thanks in advance !

I think it's a debugger to check if reader is null because if it is null

it will output null and it also check if it is ready output would be true or false.

Yannixa at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 10

Without looking at all your code (and I don't really want to), all I can think of is that the reader you initialise in your setUpNetworking method is different to the one in your run method. Do you have different local variables or instance variables? Are they in different classes?

floundera at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 11

well first i have

BufferedReader reader;

PrintWriter writer;

Socket sock;

in then i initialise it in the setUpNetworking method, so their the same.

I might have to recopy the code and maybe it will work, i might of missed something the first time

The_Undeada at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 12

I'll bet it's a scoping issue. I'll bet your reader that is being initialized is not the same reader as the one that is trying to do the reading....

petes1234a at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 13

> I'll bet it's a scoping issue. I'll bet your reader

> that is being initialized is not the same reader as

> the one that is trying to do the reading....

so if it was, would i be able to fix by changing a few variable names?

The_Undeada at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 14

> so if it was, would i be able to fix by changing a

> few variable names?

If it were, you'd have to declare your reader as a class variable. Then when you initialize it, make sure that you don't redeclare it (else you are only initializing a newly created local variable, not the class variable).

petes1234a at 2007-7-29 18:45:08 > top of Java-index,Java Essentials,New To Java...
# 15

Sorry im a noob lol but what do you mean by, declare your reader as a class variable?

The_Undeada at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 16

class MyClass {

// instance or member variables

// these are visible to all methods of the class

}

floundera at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 17

oh, ok...ill go ahead and try changing some stuff to see if that works

Edit - ok so i tried that and now i get

java.lang.NullPointerException

at userChat$IncomingReader.run(userChat.java:82)

at java.lang.Thread.run(Thread.java:619)

were line 82 is the incoming.append(message + "\n");

Message was edited by:

The_Undead

The_Undeada at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 18

public class Fubar2

{

// here's a class variable or field. It is declared in the

// class Fubar2, and not declared within any method

private Integer classIntegerVariable;

// this method initializes the class variable

public void initClassIntegerVar(int myInt)

{

classIntegerVariable = new Integer(myInt);

}

// this method uses the class variable

public void methodUseClassVar()

{

System.out.println(classIntegerVariable);

}

// this method tries to use the class variable

// but actually uses a different local variable, a shadow variable

// with the same name.

public void methodUseLocalVar()

{

// I've redeclared this -- it's a different variable now

Integer classIntegerVariable;

// now this won't work since the var has not been initialized

System.out.println(classIntegerVariable); // !!!! ERROR !!!!

}

public static void main(String[] args)

{

Fubar2 f2 = new Fubar2();

f2.initClassIntegerVar(4);

f2.methodUseClassVar();

f2.methodUseLocalVar();

}

}

petes1234a at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 19

perhaps you should post all your code.

petes1234a at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 20

Well here is the chat code

public class userChat

{

JTextArea incoming;

JTextField outgoing;

BufferedReader reader;

PrintWriter writer;

Socket sock;

public void chat()

{

JFrame chatFrame = new JFrame("Acidmods Chat");

JPanel mainPanel = new JPanel();

incoming = new JTextArea(15, 50);

incoming.setLineWrap(true);

incoming.setWrapStyleWord(true);

incoming.setEditable(false);

outgoing = new JTextField(30);

JScrollPane qScroller = new JScrollPane(incoming);

qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

JButton sendButton = new JButton("Send");

sendButton.addActionListener(new sendListener());

mainPanel.add(qScroller);

mainPanel.add(outgoing);

mainPanel.add(sendButton);

Thread readerThread = new Thread(new IncomingReader());

readerThread.start();

chatFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);

chatFrame.setSize(600, 400);

chatFrame.setVisible(true);

}

private void setUpNetworking()

{

try

{

sock = new Socket("ip", 6928);

InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());

reader = new BufferedReader(streamReader);

writer = new PrintWriter(sock.getOutputStream());

System.out.println("Networking Established");

}

catch(Exception e)

{

//System.out.print("Error: " + e);

e.printStackTrace();

}

}

public class sendListener implements ActionListener

{

public void actionPerformed(ActionEvent ev)

{

try

{

writer.println(outgoing.getText());

writer.flush();

}

catch(Exception e)

{

System.out.println("Error: " + e);

e.printStackTrace();

}

outgoing.setText("");

outgoing.requestFocus();

}

}

public class IncomingReader implements Runnable

{

public void run()

{

String message;

try

{

System.out.println(reader);

System.out.println(reader.ready());

while((message = reader.readLine()) != null)

{

System.out.println("read" + message);

incoming.append(message + "\n");

}

}

catch(Exception ex)

{

System.out.println("Error: " + ex);

ex.printStackTrace();

}

}

}

}

Message was edited by:

The_Undead

The_Undeada at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 21

Do you ever actually call setUpNetworking?

doremifasollatidoa at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 22

Live,

Just post your whole class... it's not proprietory code or anything... this debugging blind is a LOT of a joke.

Message was edited by: corlettk: Ooops... I missed page 2

corlettka at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 23

One other thing sorry... it's unsafe to mutate the Swing controls on a background thread... checkout the new (1.6) SwingWorker class, especially the publish & process methods.

corlettka at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 24

Here's one I prepared earlier. I appologise for the shocking netbeans generated Swing GUI code.

package krc.chat.client;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.MulticastSocket;

import java.net.SocketException;

import java.net.UnknownHostException;

import java.util.List;

import java.util.concurrent.ExecutionException;

import javax.swing.JOptionPane;

import javax.swing.SwingWorker;

/**

* chat.client.ClientForm.java - A wee GUI for a wee chat app.

* @author Keith

*/

public class ClientForm extends javax.swing.JFrame {

private class MessageFetcherator

extends SwingWorker<Void, String>

// The 2nd arg is the type of "intermediate results" to be "published".

{

// doInBackground is invoked in the background thread, it publishes messages

// as they arive to a List of Strings which is then picked up and displayed

// by the process method which runs periodically on the EDT.

@Override

public Void doInBackground() {

MulticastSocket socket = null;

InetAddress address = null;

try {

socket = new MulticastSocket(4446);

address = InetAddress.getByName("230.0.0.1");

socket.joinGroup(address);

while (!isCancelled()) {

byte[] buf = new byte[256];

DatagramPacket packet = new DatagramPacket(buf, buf.length);

socket.receive(packet); //thread blocks here

String response = new String(packet.getData(), 0, packet.getLength());

System.out.println(response);

publish(response);

}

} catch (Exception ex) {

ex.printStackTrace();

} finally {

try {

if(socket!=null)socket.leaveGroup(address);

} catch (Exception e) {

e.printStackTrace();

}

socket.close();

socket = null;

}

return null;

}

// process is invoked in the event dispatch thread whenever swing feels like it

// so it could process several messages at once, but it's safe to mutate the

// swing controls on this thread.

@Override

protected void process(List<String> messages) {

for(String message : messages) {

displayTextArea.append(message+"\n");

}

}

}

private class MessageSenderator {

private String username = null;

private DatagramSocket socket = null;

private InetAddress address = null;

MessageSenderator(String username) throws SocketException, UnknownHostException {

this.username = username.toLowerCase();

this.socket = new DatagramSocket();

this.address = InetAddress.getByName("localhost");

}

public void send(String message) throws IOException {

// send the message

message = username+": "+message;

byte[] bytes = new byte[256];

DatagramPacket packet = new DatagramPacket(bytes, bytes.length, this.address, 4447);

byte[] messageBytes = message.getBytes();

packet.setData(messageBytes, 0, messageBytes.length);

this.socket.send(packet);

}

public void close() {

if(socket!=null)socket.close();

}

}

MessageSenderator sender = null;

/** Creates new form ClientForm */

public ClientForm(String username) {

this.setTitle("Chat - "+username);

// build the GUI

initComponents();

// select all the text in the input field and give it focus

inputTextField.setSelectionStart(0);

inputTextField.setSelectionEnd(inputTextField.getText().length());

inputTextField.requestFocus();

try {

sender = new MessageSenderator(username);

sender.send(username+" joins the chat.");

} catch (Exception ex) {

ex.printStackTrace();

}

// setup a background thread which recieves messages from the server

// and appends them to the TextArea on the form.

(new MessageFetcherator()).execute();

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jScrollPane2 = new javax.swing.JScrollPane();

displayTextArea = new javax.swing.JTextArea();

inputTextField = new javax.swing.JTextField();

sendButton = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

displayTextArea.setColumns(20);

displayTextArea.setFont(new java.awt.Font("Arial", 0, 10));

displayTextArea.setRows(5);

displayTextArea.setTabSize(4);

displayTextArea.setFocusable(false);

jScrollPane2.setViewportView(displayTextArea);

inputTextField.setText("... type your message here ...");

inputTextField.setName("messageText");

inputTextField.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

inputTextFieldActionPerformed(evt);

}

});

sendButton.setText("Send");

sendButton.setName("sendButton");

sendButton.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

sendButtonActionPerformed(evt);

}

});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

.addComponent(inputTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addContainerGap())

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)

.addContainerGap())

);

pack();

}// </editor-fold>

private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {

sendButtonActionPerformed(evt);

}

private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {

try {

String message = inputTextField.getText();

inputTextField.setText("");

if ("".equals(message.trim())) return;

sender.send(message);

} catch (Exception e) {

e.printStackTrace();

JOptionPane.showConfirmDialog(this, e.toString(), "Exception", JOptionPane.ERROR_MESSAGE);

}

}

// Variables declaration - do not modify

private javax.swing.JTextArea displayTextArea;

private javax.swing.JTextField inputTextField;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JButton sendButton;

// End of variables declaration

}

and here's the client.java ....

package krc.chat.client;

import javax.swing.JOptionPane;

public class Client

{

/**

* Create the GUI and show it.

* For thread safety, this method should be invoked from the event-dispatching thread.

*/

private static void createAndShowGUI(String username) {

new ClientForm(username).setVisible(true);

}

public static void main(String[] args) {

//tell the event-dispatching thread to create & show this application's GUI.

final String username = (args.length==0 ? askUsername() : args[0]);

javax.swing.SwingUtilities.invokeLater(

new Runnable() {

public void run() {

createAndShowGUI(username); //TODO get username from command line param?

}

}

);

}

private static String askUsername() {

String s = (String)

JOptionPane.showInputDialog(

null

, "username"

, "Enter username"

, JOptionPane.QUESTION_MESSAGE

)

;

return(s==null||"".equals(s) ? "guest" : s);

}

}

Message was edited by: corlettk - frikkin code tags again

corlettka at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...
# 25

> Do you ever actually call setUpNetworking?

....OMG im am an idiot, lol....it works now....

The_Undeada at 2007-7-29 18:45:13 > top of Java-index,Java Essentials,New To Java...