我有一个名为Order
的对象,我想在活动之间传递。目前我正在使用Parcelable
来执行此操作。
public class Order implements Parcelable {
private String email;
private Long timestamp;
private List<OrderItem> items;
public Order() { }
private Order(Parcel in) {
email = in.readString();
timestamp = in.readLong();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(email);
if (timestamp == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeLong(timestamp);
}
dest.writeTypedList(items);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Order> CREATOR = new Creator<Order>() {
@Override
public Order createFromParcel(Parcel in) {
return new Order(in);
}
@Override
public Order[] newArray(int size) {
return new Order[size];
}
};
// Getters
...
}
items
字段是实现List
接口的OrderItem
个Parcelable
个对象。
public class OrderItem implements Parcelable {
private String orderedClothingId;
private int quantity;
public OrderItem() { }
public OrderItem(String orderedClothingId, int quantity) {
this.orderedClothingId = orderedClothingId;
this.quantity = quantity;
}
private OrderItem(Parcel in) {
orderedClothingId = in.readString();
quantity = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(orderedClothingId);
dest.writeInt(quantity);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<OrderItem> CREATOR = new Creator<OrderItem>() {
@Override
public OrderItem createFromParcel(Parcel in) {
return new OrderItem(in);
}
@Override
public OrderItem[] newArray(int size) {
return new OrderItem[size];
}
};
}
现在要将Order
名为order
的对象从一个活动传递到另一个活动,我会执行以下操作:
Intent intent = new Intent(mContext, ActivityTwo.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(ORDER_DETAIL_INTENT_EXTRA_KEY, order);
mContext.startActivity(intent);
在ActivityTwo
我收集Order
对象,如下所示:
Bundle data = getIntent().getExtras();
assert data != null;
mOrder = data.getParcelable(ORDER_DETAIL_INTENT_EXTRA_KEY);
但是,当我在items
中记录Order
对象中包含的ActivityTwo
字段时,它是null
。如何在没有Order
列表为空的活动之间传递原始的非空items
对象?
答案 0 :(得分:1)
从第一眼看,你似乎在你的parcelable中传递了不同的不同键
第一个ORDER_DETAIL_INTENT_EXTRA_KEY
,第二个CLOTHING_ADMIN_DETAIL_INTENT_EXTRA_KEY
。它们应该是相同的,所以选择哪一个。
此外,您可以使用getIntent().getParcelableExtra()
,而不必使用Bundle
答案 1 :(得分:1)
首先,您错过了使用dest = in.readTypedList(emptyList, CREATOR);
但第二个也是更重要的,你需要写/读相同数量的参数,因为你在writeToParcel中有一个if,你在阅读时需要相同:
private Order(Parcel in) {
email = in.readString();
if(in.readByte() == 1)
timestamp = in.readLong(); //here to skip just like the writeToParcel
in.readTypedList(items = new ArrayList<OrderItem>(), OrderItem.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(email);
if (timestamp == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeLong(timestamp);
}
dest.writeTypedList(items);
}