LinkedList Iteration Exception - java

I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks

Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.

My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.

You never check to see if im is null. I suspect it is.

One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?

Either im is null or order.getOrderID() is returning null.

Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}

It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null

Related

Checking if Parse.com class is (undefined)

I'm trying to catch an exception. I thought that checking whether the String is empty would help, but it doesn't seem to work. The value in the actual column for the object in my class is "(undefined)". It seems to be that by default. How can I explicitly check to see if it is undefined?
notifications.getString(ParseConstants.KEY_FEED_TYPE).isEmpty()
Heads up. The following doesn't work either:
notifications.getString(ParseConstants.KEY_FEED_TYPE).equals("(undefined)");
it's checking using Android default function like
if (!TextUtils.isEmpty(notifications.get(ParseConstants.KEY_FEED_TYPE))) {
// its not null value success
} else {
// here getting to null value Fail
}
I did the following. Instead of looking for a String (in which case the field entry would be truly empty, and not (undefined)), I checked to see if the object was null after dropping the String from getString.
if (notifications.get(ParseConstants.KEY_FEED_TYPE) != null) {
// Do something.
} else {
// Do something else.
}

!array[0].isEmpty() returning NullPointer?

Here's my code:
if (!quizDescs[0].isEmpty()) {
mDescText.setText(quizDescs[0]);
} else {
mDescText.setVisibility(View.INVISIBLE);
}
So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.
Am I checking the condition right? Why is it returning a NullPointer?!
ANSWER:
if (quizDescs[0] == null) {
mDescText.setVisibility(View.INVISIBLE);
} else {
mDescText.setText(quizDescs[0]);
}
if quizDesc[0] is String, you can do
if(!StringUtility.isEmptyOrNull(quizDesc[0])){
mDescText.setText(quizDescs[0]);
}else {
mDescText.setVisibility(View.INVISIBLE);
}
By the way,
Null and being empty is not same
Consider
String s; //Initialize to null
String a =""; //A blank string
Its always a good practise to use
try{
//Your code here..
}catch(Exception e){
e.printStacktrace();
}
If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.
Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.
Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :
if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
....
} else {
....
}
You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.
The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.
You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).

Comparing string array in JAVA

I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))

NullPointerException, logical shortcut

Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.

Nullpointer exception

There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both

Categories

Resources