Search code examples
androidnullpointerexceptionparcel

Null Pointer Exception when packaging a Parcel


I just got the first report of a Null Pointer Exception that makes no sense to me at all...

java.lang.NullPointerException
at com.kd7uiy.hamfinder.Subjects.DxccSubject.a(Unknown Source)
at com.kd7uiy.hamfinder.Subjects.AbstractSubject.writeToParcel(Unknown Source)
at android.os.Parcel.writeParcelable(Parcel.java:1254)
at android.os.Parcel.writeValue(Parcel.java:1173)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1627)
at android.os.Parcel.writeBundle(Parcel.java:605)
at com.kd7uiy.hamfinder.Broker.writeToParcel(Unknown Source)
at android.os.Parcel.writeParcelable(Parcel.java:1254)
at android.os.Parcel.writeValue(Parcel.java:1173)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1627)
at android.os.Parcel.writeBundle(Parcel.java:605)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:2260)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3186)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5233)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)

And the referenced function is this:

@Override
Bundle packageContents() {
    Bundle out = new Bundle();
    out.putInt("State", getState());
    return out;
}

Note that the NPE was not in getState(). How is it possible that a NPE could be caused? The only thing I can think of is that the class was actually destroyed in the process of calling the function, but that doesn't really make sense. Any ideas?

Just for the fun of it, here's the spec on getState. It's a part of Abstract Subject, which the entire function is the following:

Type mState = null; //Defined at the class level

public Type getState() {
    return mState;
}

AbstractSubject is a generic class, in the case of DxccSubject, the type is Integer.


Solution

  • This explanation seems very trivial so I doubt you haven't thought of it, but...

    Bundle.putInt() receives an int value. Your getState() generic method returns Integer for this class. In Java, auto-unboxing a null Integer to int (or any of the other boxed primitives, such as Long, Float, &c) will throw a NullPointerException.Probably because the compiler just replaces it with getState().intValue().

    Isn't it possible that mState is simply null when writeToParcel() is called?