我试图使我的一个类可拆分,但是在读取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)
......
是什么原因造成的,我该如何解决?
最佳答案
看来time
对象在写入Parcel
时为空,而在以后解组该对象时会得到。当java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:60)
尝试初始化Parcel
时,我可以从ByteArrayInputStream
行中说出来。
将时间对象写入包裹时,请确保其不为空。
Alternatively,分别使用parcel.writeValue(time);
和readValue()
,文档说它接受null
和? implements Serializable
作为对象。