嵌套parcelable对象不读

我想包裹一个包含一些string/整型variables和一个对象variables的对象。 string和int正在工作,但不是嵌套的对象。 我知道我不得不这样也可以parcelable,但我显然做错了=。 在我的嵌套类中, writeToParcel方法被调用(我使用Log.d()调用),但是createFromParcel()不调用。 我最终得到一个null对象。 这是我的简化代码:

 public class MyClass implements Parcelable { public MyClass() { } private Integer id; private String name; private MyOtherClass otherClass = new MyOtherClass(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public OtherClass getOtherClass() { return otherClass; } public void setOtherClass(OtherClass otherClass) { this.otherClass = otherClass; } public static final Parcelable.Creator<MyClass> CREATOR = new Parcelable.Creator<MyClass>() { public MyClass createFromParcel(Parcel in) { return new MyClass(in); } public MyClass[] newArray(int size) { return new MyClass[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(id); dest.writeParcelable(otherClass, flags); } private MyClass(Parcel in) { name = in.readString(); id = in.readInt(); otherClass = (OtherClass) in.readParcelable(OtherClass.class.getClassLoader()); } } class MyOtherClass implements Parcelable { public OtherClass() { } private String resourcePreviewURL; public String getResourcePreviewURL() { return resourcePreviewURL; } public void setResourcePreviewURL(String resourcePreviewURL) { this.resourcePreviewURL = resourcePreviewURL; } public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { Log.d("parcel", "write to parcel"); // this gets called out.writeString(resourcePreviewURL); } public static final Parcelable.Creator<MyOtherClass> CREATOR = new Parcelable.Creator<MyOtherClass>() { public MyOtherClass createFromParcel(Parcel in) { Log.d("parcel", "create from parcel"); // this doesn't get called return new MyOtherClass(in); } public ResourcePreviews[] newArray(int size) { return new ResourcePreviews[size]; } }; private OtherClass(Parcel in) { Log.d("parcel", "read from parcel"); // this doesn't get called resourcePreviewURL = in.readString(); } } 

我通过改变从包裹写入/读取的顺序来解决这个问题。 我做了dest.writeParcelable(otherClass, flags);otherClass = (OtherClass) in.readParcelable(OtherClass.class.getClassLoader()); 呼吁成为他们的第一个方法,并开始工作。 这是一个问题吗?

 @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(otherClass, flags); dest.writeString(name); dest.writeInt(id); } private MyClass(Parcel in) { otherClass = (OtherClass) in.readParcelable(OtherClass.class.getClassLoader()); name = in.readString(); id = in.readInt(); }