0

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!

Anthony
  • 7,638
  • 3
  • 38
  • 71
  • is your 'key' not null? or mValues? or 'values' in new Date() – Rusheel Jain Mar 14 '16 at 00:44
  • Was a little too concise there. I am checking for null `values`. Regardless, I'd be getting a different error for null key, mValues, or values I believe. – Anthony Mar 14 '16 at 00:52
  • Have you tried to debug? What is the value of `Meta.Data.TIMESTAMP`? – Vasily Kabunov Mar 14 '16 at 03:10
  • Updated the question. I can now handle this error since I know the general cause, but I don't entirely understand the way the exception and the stack trace are working, so if anyone has am explanation that'd be great. – Anthony Mar 14 '16 at 14:35

1 Answers1

0

I had the same error, worked around by checking if such key exists with containsKey().

values.containsKey(Meta.Data.TIMESTAMP)

I am suspecting usage of weakreference to database results. Not exactly sure. Just adding a workaround here for this strange error.

user303730
  • 384
  • 1
  • 5
  • 15