Problems with NumberFormatException - java

I have noticed a strange problem with my program that I just can not figure out. I have included the method that has been flagged up, and the Error that was given. What's confusing me is that I have duplicated this method about 40 times on other buttons, changing only the 'engtf4' to another source where needed. They work perfectly with no errors, yet are written exactly the same. Adding further confusion, the method is executed exactly as intended(even though the error message below is given)?
I have looked around the net for similar problems using keywords - java.lang.NumberFormatException: For input string: "", I did however notice that all the example sites I saw had reference to a particular value in qoute marks. For example, -java.lang.NumberFormatException: For input string: "2345". I would appreciate any help I could get, thanks.
METHOD SOURCE CODE:
if (a.getSource() == engBuy4){
getItems();
q = engtf4.getText();
qq = Long.parseLong(q); //////////// LINE 13086
if (qq > 1000000 || total > 1000000){
Error.setText("You can ship a maximum of 1 million items.");
engtf4.setText("");
}
if (qq <= 1000000 && total <= 1000000){
if (qq > rem){
Error.setText("You can ship " + rem + " more items");
engtf4.setText("");
}
if (qq <= rem){
buyShrEng();
engtf4.setText("");
}
}
ERROR MESSAGE:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at DopeWars.DopeWars.mouseReleased(DopeWars.java:13086)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Long.parseLong() throws a NumberFormatException if the passed string is not a parsable long value. In your case, you are passing an empty string (probably because the user did not enter anything in the input field). You can verify this easily:
...
Long.parseLong("");
...
java.lang.NumberFormatException: For input string: ""
You should always be prepared to catch this exception (besides empty strings, the exception is thrown if the user enters anything which is not a Long), and show an appropriate error message to the user, something like
try {
qq = Long.parseLong(q);
} catch(NumberFormatException nfe) {
// show error message like "The string ... you entered is not a number."
...
}
If you want to treat an empty string as 0 (if that is reasonable for your use case), you can do something like (still requires the try/catch block to catch any other invalid inputs):
try {
long qq = 0;
if (q != null && !q.isEmpty()) {
qq = Long.parseLong(q);
}
...
} catch(NumberFormatException nfe) {
// show error message like "The string ... you entered is not a number."
...
}
In addition to that, instead of duplicating code dozens of times, you should check which are the variable parts of your code and replace them with variables, so that you can reuse the code instead of duplicating it.

It is raising the NumberFormatException, Since the argument passed to the parse() Method, is not parsable. What i mean to say is, input is invalid here.
Checkout the following link :)
http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html

It seems that the value entered is an empty string :java.lang.NumberFormatException: For input string: ""
So before parsing to long you should test if the string value is empty or not.
In any ways you should catch the java.lang.NumberFormatException to put a default value if the parse doesn't succeed

We cannot parse empty space or null to long.If we try that,the number format exception arise.
so before parsing add the if statement to check the value is present or not.
if(q!=null && !"".equals(q))
qq=Long.parse(q);
It's good to use exception handling in these situations

Related

Java: "unknown source" error with unfolding maps package

BACKGROUND
I'm trying to build a map of earthquake events with data parsed from an RSS feed using the "Unfolding maps" library in Java (this is part of the Coursera course on OOP with Java). In theory, the data from the feed gets parsed into properties of the earthquake (location, magnitude, ...) which then form the basis for these marker objects that get displayed on a map. The libraries that are used are "Processing" and the "Unfolding Maps" library.
PROBLEM
Theres an "Unknown Source" error in the part, where I want to set the color property of the earthquake marker, depending on the magnitude of the event (ie. magnitude > 3 is "yellow").
Here's the error message:
Exception in thread "Animation Thread" java.lang.NullPointerException
at de.fhpotsdam.unfolding.marker.AbstractMarker.getProperty(Unknown Source)
at module3.EarthquakeCityMap.setup(EarthquakeCityMap.java:101)
at processing.core.PApplet.handleDraw(PApplet.java:2365)
at processing.opengl.PJOGL$PGLListener.display(PJOGL.java:873)
at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:690)
at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:672)
at javax.media.opengl.awt.GLCanvas$10.run(GLCanvas.java:1383)
at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1277)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1131)
at javax.media.opengl.awt.GLCanvas$11.run(GLCanvas.java:1394)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
And here is the code
for (Marker marker:markers) {
if ((int) (marker.getProperty("magnitude")) > 3) {
System.out.println("trying to set the colour to yellow");
//marker.setColor(yellow);
}
}
The line with "setColor(yellow)" is commented out, as it seems that this is a problem of its own (may or may not have to do with it).
Anybody have an idea where this may come from and what I could read up on to better understand the problem? I'm pretty new to programming so any advice on how to learn the process of tracing errors / finding out the cause of a problem would be fantastic.

MATLAB reports "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"

I wonder about a Java error that is repeatedly occurs in MATLAB. It typically occurs when MATLAB is doing some heavy stuff with Java. This can for example be holding Ctrl + Z or Ctrl + Y.
I did by mistake erase the error message before I copied it, but I think that I can pass the core of the problem anyway.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Why did this error occur? I have found some information about this from MATLAB r2007, this due to that Java Swing is thread unsafe and MATLAB lacked support to ensure thread safety. However, that is supposed to have been fixed in MATLAB r2008b. So why do I get it now?
Here is the full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.netbeans.editor.BaseDocument.notifyUnmodify(BaseDocument.java:1465)
at org.netbeans.editor.BaseDocument.notifyModifyCheckEnd(BaseDocument.java:816)
at org.netbeans.editor.BaseDocumentEvent.redo(BaseDocumentEvent.java:336)
at javax.swing.undo.UndoManager.redoTo(Unknown Source)
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
at org.netbeans.editor.ActionFactory$RedoAction.actionPerformed(ActionFactory.java:767)
at org.netbeans.editor.BaseAction.actionPerformed(BaseAction.java:259)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at com.mathworks.widgets.SyntaxTextPaneBase.processKeyEvent(SyntaxTextPaneBase.java:1187)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Well, based on your stack trace, probably there isn’t any definitive answer to your question, as you have already seen in MATLAB's forum, but given this line, I think there's a possible explanation:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at javax.swing.undo.UndoManager.redoTo(Unknown Source) // <-- here!
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
...
UndoManager class keeps an internal collection of UndoableEdit objects. This collection is actually inherithed from its superclass: CompoundEdit.
The internal implementation of UndoManager#redo() and UndoManager#redoTo(UndoableEdit edit) looks like this:
public class UndoManager extends CompoundEdit implements UndoableEditListener {
...
public synchronized void redo() throws CannotRedoException {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
if (edit == null) {
throw new CannotRedoException();
}
redoTo(edit);
} else {
super.redo();
}
}
...
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
boolean done = false;
while (!done) {
UndoableEdit next = edits.elementAt(indexOfNextAdd++);
next.redo(); // NPE here?
done = next == edit;
}
}
...
}
Considering this implementation and given that Swing's Event Dispatch Thread (EDT) is prone to cause troubles, I think it's probably a threading issue between MATLAB threads and the EDT. Specifically speaking this MATLAB-invoked method could be the source of the problem:
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
Since you say MATLAB needs to do heavy work, it's not unreasonable to think this method is trying to redo some edit that might well not be available anymore or might not be available yet, due to synchronization problems with the EDT.
You can find the ~/.matlab folder which contains MATLAB settings, etc. Use ls -la to show all hidden files and folders.
Open a terminal and execute sudo chmod 757 -R ~/.matlab.
Similarly there is a folder, MATLAB, in Documents.
Execute sudo chmod 757 -R ~/Documents/MATLAB.
Now restart MATLAB without root privileges. It worked for me on Ubuntu 14.04 (Trusty Tahr) and MATLAB 2015a.

NUllPointerException on non null String

I am working an a small database assignment, and I seem to get a weird nullPointerException where I cannot find the problem
The following snippet is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at interfaces.FindDueActivityForFriend$1.actionPerformed(FindDueActivityForFriend.java:65)
at java.awt.Button.processActionEvent(Unknown Source)
at java.awt.Button.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
As you can see the problem occurs in the 65 of the FindDueActivityForFriend class, and to be more specific in this code snippet:
friendSearch = friendSearchField.getText();
console.out("Searching for the name that was entered");
console.out("friendSearch variable is: " + friendSearch );
if(con.GetNameExcists(friendSearch )){
//more code
the error occurs at the if statement.
In this if statement a class is called that connects to the database, checks if a name is already in the database, and then returns a true if that name is already in the database.
I have used that specific method around 10 times around the program without problems, but not this time.
the console.out("String"); that I am calling just before it is for a small console windows that I made that just prints what I tell it to, this is to have a console when not running the application out of for example eclipse.
I tried printing the variable just to see what it was, and it is not null.
following is a copy paste of the console:
[Wed May 14 20:04:26 CEST 2014] [INFO] Opened the findDueForFriend screen
[Wed May 14 20:04:30 CEST 2014] [INFO] Searching for the name that was entered
[Wed May 14 20:04:30 CEST 2014] [INFO] FriendSearch variable is: Ylva
I went on into ant debugger, and is doesn't even go in the method, it throws the nullpointer before actually opening the method
I don't have a clue what I am doing wrong anymore so if anyone has any suggestions please post them.
just for completeness here is the declaration of the variable aswell:
String friendSearch;
public FindDueActivityForFriend(Console Console){
console = Console;
friendSearch = "";
I even tried declaring the String as an empty string, not sure if that makes it not null but I think it should, and the console window clearly shows that the string contains something before throwing the nullpointer exception...
If it occurs in this if statement
if(con.GetNameExcists(friendSearch ))
and you know that friendSearch is not null, then con must be null, in order to get a NullPointerException in the if statement.
the only possibility with the below code is
if(con.GetNameExcists(friendSearch ))
either con is null or friendSearch is null which you might be accessing at the
begining of the method and performing some operation like friendSearch.caoncat or something.
mostly it should be con is null it seems.
try to print con value inside log.
if con.getNameExcists(...) return Boolean instead of boolean and possibly returns null, then you get a NullPointerException from auto-unboxing.

Java applet throws error in remove object from Iterator array

Welcome, i am programming a simple RPG game in java applet. It is getting more and more complicated and many errors are thrown to my face. Today i have problem with .remove(); method.
Exception in thread "AWT-EventQueue-1" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.remove(Unknown Source)
at rpg.main.paint(main.java:365)
at rpg.main.update(main.java:331)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
That's how error log looks like. Code of program:
main.java
As we can see error appears in paint methid in the end of program, but i dont know maybe it is caused by wrong initiation in the beginning of program?
public void initLocatables()
public void initLocatables2()
And i have to admit that they are called in main while loop in run method.
These is place where error apears, and below in comment i have included previous method that has also thrown error, both in remove();
for (Iterator i = locatablesArray.listIterator(); i.hasNext();) {
Locatable l = (Locatable) i.next();
l.draw(g);
i.remove();
}
/*while(itrLocatables.hasNext())
{
Locatable l = itrLocatables.next();
l.draw(g);
l.remove();
}*/
Thank you for any reply.
Maybe when you call repaint() in run(), paint() is queued to EDT and called as soon as possible; while iterating locatablesArray a call to initLocatables2() in run() is done another time and the re-init of locatablesArray in the same time the code of paint() will produce the error.
My advice is to separate init operation in a specific init section and call it once, the run your main loop.
Just another thing: why are you init a Iterator (class field itrLocatables) in initLocatables2()? Use iterator when needed if possible.
Hope to be clear, English is not my native language.
You cannot remove objects from a list/map while you are iterating them. That's the cause of the ConcurrentModificationException
i.remove();
If you will draw all the Locatable elements, and then clear the collection, maybe you should draw them all first, and then clear the collection, instead of removing them on the fly.
for (Iterator i = locatablesArray.listIterator(); i.hasNext();) {
Locatable l = (Locatable) i.next();
l.draw(g);
}
// Clear everything from the list
locatablesArray.clear();
java.util.ConcurrentModificationException
Another approach is to use a for loop through the locatablesArray starting at the end vs the beginning. That way any elements that are removed won't change the location of elements of the array that are yet to be scanned.

Java ObjectInputStream readObject Throws NullPointerException

I am using an ObjectInputStream and ObjectOutputStream for my client to talk to a server over TCP. The client is not able to receive a response back from the server... when I step through in debug mode the response goes through fine. However, if I run the program without a break point it will throw a NullPointerException exception.
Initialization:
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
Socket socket = null;
socket = new Socket(server, port);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
Code that breaks:
try
{
oos.writeObject(request);
serverResponse = (Message) ois.readObject();
output.append(serverResponse.data + "\n");
}
catch(Exception ex)
{
System.err.println("Error adding car to server: " + ex.getMessage());
return;
}
The code above is throwing the NullPointerException. If I use a break point and step through, I get a server response just fine. I have confirmed that in every instance the server is reading the
Any help would be greatly appreciated!
EDIT STACK TRACE AT EX:
java.lang.NullPointerException
at CarInventoryClient.actionPerformed(CarInventoryClient.java:251)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I suggest you flush the output stream before attempting to read the input stream.
The variable ex shouldn't be null. Can you give us the exact line the exception occurs on.
You should print the whole message. I suspect not printing the type and line the exception is occurring is not helping. If you have an exception with no message getMessage() will return null
try
ex.printStackTrace();
I think the output of this line is probably confusing you:
System.err.println("Error adding car to server: " + ex.getMessage());
An exception does not require a message so it is perfectly normal (as well as a bit inconvenient) that this prints:
Error adding car to server: null
By only printing the exception message you are missing out on logging crucial information such as the exception type as well as the exceptions stack trace. You are better off calling ex.printStackTrace(). Which prints the exception class, message and the stack trace of the exception.
(An elaboration of a comment above, for didactic reasons. OP has confirmed.)
If you get a stack trace that begins with a given line, it means the throw happened on that very line - not within a method called from that line. So looking at the line in question:
> java.lang.NullPointerException
> at CarInventoryClient.actionPerformed(CarInventoryClient.java:251)
serverResponse = (Message) ois.readObject();
The only way this very line could throw an NPE is if ois is null.
This was a race condition.
ois = new ObjectInputStream(socket.getInputStream());
The above line was causing the thread to block in my class's constructor. Java's documentation states that it will block until input headers are received. The action handler was sending then receiving a packet from the server - this woke the constructor code back up and finished the initialization.
When there was a thread sleep, or the debugger was attached, the constructor code would complete before the data was received. However, in real time execution, readObject was being called before the unblocked initialization could finish. This is why ois was being seen as null.

Categories