4

我必须将数据对象从一个活动传递到另一个活动。最好的方法是使用 Parcelable。数据对象有一些带有 setter 和 getter 方法的字段。在设置一些字段并将对象传递给另一个活动后,我观察到字段值与其他字段值互换。写入包裹和读取包裹的字段顺序是相同的。

public void writeToParcel(Parcel out, int flags) {
    out.writeInt(id);
    out.writeString(appNo);
    out.writeString(this.policyNo);
    out.writeInt((int)this.AppRcptDt.getTime());
    out.writeString(this.currentStatus);
    out.writeString(this.productCd);
    out.writeDouble(this.sumAssured);
    out.writeDouble(this.modalPremium);
    out.writeDouble(this.annualPremium);
    out.writeString(this.paymentMode);
    out.writeString(this.branchCd);
    out.writeString(this.branchName);
    out.writeString(this.insuredName);
    out.writeString(this.auraStatus);
    out.writeString(this.ownerName);
    out.writeString(this.agentCd);
    out.writeString(this.billingMode);
}

private ApplicationTrackerDO(Parcel in) {
    id=in.readInt();
    this.appNo = in.readString();
    this.policyNo = in.readString();
    this.AppRcptDt = new Date(in.readLong());
    this.currentStatus = in.readString();
    this.productCd = in.readString();
    this.sumAssured = in.readDouble();
    this.modalPremium = in.readDouble();
    this.annualPremium = in.readDouble();
    this.paymentMode = in.readString();
    this.branchCd = in.readString();
    this.branchName = in.readString();
    this.insuredName = in.readString();
    this.auraStatus = in.readString();
    this.ownerName = in.readString();
    this.agentCd = in.readString();
    this.billingMode = in.readString();
}

字段值的差异

4

4 回答 4

11

不同的不是顺序而是数据类型,从前 4 行开始,你写的是 int、string、string、int,然后你读的是 int、string、string、long。我没有进一步检查,您必须匹配读写操作的顺序和数据类型。

于 2012-04-16T06:21:27.113 回答
1

你正在写int

out.writeInt((int)this.AppRcptDt.getTime());

但是阅读时间长

this.AppRcptDt = new Date(in.readLong());
于 2012-04-16T06:21:50.327 回答
0

我为日期对象提供 null 的解决方案

@Override
    public void writeToParcel ( Parcel dest, int flags ) {
        dest.writeInt((birthday != null) ? 1 : 0); // is birthday set?
        dest.writeLong((birthday != null) ? birthday.getTime() : 0);
    }

    public void readFromParcel ( Parcel in ) {
        if(in.readInt() == 1) {
            birthday = new Date(in.readLong());
        } else {
            in.readLong(); // ignore stored value
            birthday = null;
        }
    }
于 2013-06-25T14:02:57.080 回答
0

java.util.Date 实现可序列化:

public class Date implements Serializable, Cloneable, Comparable<Date> {

    private static final long serialVersionUID = 7523967970034938905L;

    // Used by parse()
    private static final int CREATION_YEAR = new Date().getYear();

    private transient long milliseconds;


采用:

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeSerializable(myDateField);
}
private MyClass(Parcel in) {
    myDateField = (Date)in.readSerializable();
}
于 2015-09-15T16:35:23.857 回答