In a custom SimpleCursorAdapter, I'm trying to compare a status String, with confusing results.
My string is initialised from the cursor like this (and I've checked with toast
that it contains the expected values).
String visitStatus = cursor.getString(cursor.getColumnIndex(CallData.COLUMN_VisitStatus));
visitStatus can be null, Open, Cancelled or Complete.
If I try to compare visitStatus to "any string in quotes", the app crashes with a NullPointerException. Only if I compare to null do I get anything at all - and that is no use to me
if(visitStatus.equals(null)) // the app crashes with a NullPointerException
if(visitStatus == null) // doesn't crash
if(visitStatus != null) // doesn't crash
if(visitStatus == "Complete") // doesn't crash or do anything
if(visitStatus.equals("Complete")) // the app crashes with a NullPointerException.
Basically, I can compare to null, but only in the way that isn't supposed to work. I can't compare to actual strings such as "Open" or "Complete".
I'm going slightly nuts with this, and am badly missing my C# comfort zone. This particular activity is a nightmare of listfragments, contentproviders, customadapters, viewpagers, pagertitlestrips and list row xml templates!
halp!
This is because visitStatus
is null
. Whenever you try to access its methods, it crashes. ( That is: visitString.equals()
, visitString.length()
, etc., all will crash. )
However, the equality operator ( ==
) supports null
parameters on either side of it. (So, if (null == null)
is a valid check.)
You should check like this:
if (visitStatus != null && visitStatus.equals("Complete")) {
// ...
}
Or, you can do "Yoda syntax" (backwards checking), which supports null
parameters:
if ("Complete".equals(visitStatus)) {
// ...
}
Also, a final note: You cannot compare string contents using ==
(as in, you cannot do "a" == new String("a")
, nor visitString == "Complete"
). For a detailed explanation on that, see this Q&A thread .
String
should be compared using .equals()
The NullPointerException
caused because the visitStatus
is null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.