将Joda时间段和LocalDate放入包裹中?

时间:2014-09-22 17:37:49

标签: java android jodatime

我试图让我的一个类成为可分区的,但是在将Joda Time Period对象读取为可序列化时,会抛出一个NPE。

代码:

private Event(Parcel in) {
    this.id = in.readLong();
    this.scheduleId = in.readLong();
    this.entryId = in.readLong();
    this.time = (Period) in.readSerializable(); // NPE in this line.
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeLong(id);
    out.writeLong(scheduleId);
    out.writeLong(entryId);
    out.writeSerializable(time);
}

public static final Parcelable.Creator<Event> CREATOR
        = new Parcelable.Creator<Event>() {
    public Event createFromParcel(Parcel in) {
        return new Event(in);
    }

    public Event[] newArray(int size) {
        return new Event[size];
    }
};

logcat的:

09-22 22:48:47.929  32708-32708/com.vibhinna.cubs E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.vibhinna.cubs, PID: 32708
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vibhinna.cubs/com.vibhinna.cubs.ui.EventActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
            .....
     Caused by: java.lang.NullPointerException
            at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:60)
            at android.os.Parcel.readSerializable(Parcel.java:2210)
            at com.vibhinna.cubs.engine.Event.<init>(Event.java:110)
            at com.vibhinna.cubs.engine.Event.<init>(Event.java:10)
            at com.vibhinna.cubs.engine.Event$1.createFromParcel(Event.java:251)
            at com.vibhinna.cubs.engine.Event$1.createFromParcel(Event.java:249)
            at android.os.Parcel.readParcelable(Parcel.java:2104)
            at android.os.Parcel.readValue(Parcel.java:2013)
            ......

导致这种情况的原因以及如何解决?

1 个答案:

答案 0 :(得分:1)

似乎time对象在写入Parcel时为null,并且当您稍后解组该对象时会得到该对象。当java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:60)尝试初始化Parcel时,我可以从ByteArrayInputStream行说出来。

将时间对象写入宗地时,请确保该时间对象不为空。 Alternatively,分别使用parcel.writeValue(time);readValue(),文档说它接受null? implements Serializable作为对象。