我有一個叫做Order
的對象,我想在這些活動之間傳遞。目前我正在使用Parcelable
這樣做。如何在使用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
字段是實現Parcelable
接口OrderItem
的List
對象。
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);
然而,當我在中記錄Order
對象中包含的items
字段時它是null
。如何在沒有items
列表爲空的活動之間傳遞原始非空Order
對象?
當我將它添加到我的類中時,沒有方法'createTypedList'。 –
sorr,不記得創建foryou的方法,你可以使用readList和一個空列表(項目將保存值) –