Reputation: 1598
I'm perplexed about this question: Is there a situation in which the first line in the following three lines can produce java.lang.NullPointerException?
if (mJobs == null || mJobs.size() == 0) { <-- trace shows exception here
return null;
}
This exception is seen on an unrooted Android 4.4.4 phone. mJobs is declared like this:
ArrayList<Job> mJobs;
Any ideas would be highly appreciated.
Update: This crash happened one time out many thousands of runs.
Upvotes: 0
Views: 215
Reputation: 9155
No, assuming you are using java.util.ArrayList
and not your own implementation.
It would be clearer to use isEmpty()
instead of size() == 0
. I would also check to see how this code is getting called since you are returning null
in either of those two cases.
Upvotes: 1
Reputation: 11287
Edited to say that the java "short-circuit" evaluation should never cause mJobs.size() to be evaluated, you might try it anyway to see if this is where it fails.
if (mJobs == null) {
return null;
}
if (mJobs.size() == 0) { <-- trace shows exception here
return null;
}
Upvotes: 0
Reputation: 26
The problem is the or of course, or means what it says, so the run time is evaluating both sides of the or for true before moving on. Short circuit does not occur in an or evaluation, so you can combine them in a single evaluation with short circuit if you use a ternary operation. Works the same as splitting them out, just shorter.
if (mJobs == null ? true : mJobs.size() == 0) {
return null;
}
Upvotes: 0
Reputation: 166
I do not think that there is any way that your NullPointerException
is coming from that first line of code. I bet you are running code that was compiled from a different version of the source code that you are looking at leaving you to believe that the error is on a different line than it really is. I would recompile your current code and then run it fresh.
Upvotes: 3
Reputation: 481
If mJobs is null then there is the possibility to throw the null pointer exception in mjobs.size()
if (mJobs == null || (mJobs !=null && mJobs.size() == 0)) {
return null;
}
Upvotes: 0