I have a ContentValues
that I'm parsing for data. I just received a very strange crash report:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
private void populateMeta(final ContentValues values)
{
if (values == null)
return;
Date d = new Date(values.getAsLong(Meta.Data.TIMESTAMP));
...
}
When I look in getAsLong
I can't see how this could happen:
public Long getAsLong(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).longValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Long.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Long value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Long: " + value, e);
return null;
}
}
}
It should just be returning null if the field is null, no?
Update:
Tried a few things to recreate that stack trace and in the end this narrowed it down:
values = new ContentValues();
Long timestamp = values.getAsLong(Meta.Data.TIMESTAMP); // null, as expected
Date d2 = new Date(timestamp); // source of error
Now here's the interesting thing. Adding a watch on new Date(timestamp)
throws
NullPointerException: cannot unbox null value
which makes sense. However, letting that same line execute normally in code yields:
Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
Which I'm guessing is the root cause of the unbox error. I grasp unboxing, but I'm no expert, so I'd love a better explanation for why the stack trace seems so odd (and finicky) for this error. Thanks!