我必须将数据对象从一个活动传递到另一个活动。最好的方法是使用Parcelable。 dataobject有一些带有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();
}
答案 0 :(得分:11)
不是顺序而是数据类型不一样,从你编写的前4行,字符串,字符串,整数然后你读取int,string,string,long。我没有进一步检查,你必须匹配读写操作的顺序和数据类型。
答案 1 :(得分:1)
您正在撰写 int
out.writeInt((int)this.AppRcptDt.getTime());
但是阅读长
this.AppRcptDt = new Date(in.readLong());
答案 2 :(得分: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;
}
}
答案 3 :(得分:0)
java.util.Date实现Serializable:
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();
}