通过Intent传递带有arraylist的对象

时间:2016-11-16 09:06:46

标签: java android android-intent parcelable

我希望Activity2通过Intent接收对象(此对象包含其他对象的ArrayList)。 要转移的对象:

public class Card implements Parcelable {

    @SerializedName("product_name")
    private String productName;
    private String description;
    private List<Price> prices;

    public Card() {
    }

    public Card(String productName, String description, List<Price> prices) {
        this.productName = productName;
        this.description = description;
        this.prices = prices;
    }

    protected Card(Parcel in) {
        productName = in.readString();
        description = in.readString();
    }


    public static final Creator<Card> CREATOR = new Creator<Card>() {
        @Override
        public Bundle createFromParcel(Parcel in) {
            return new Card(in);
        }

        @Override
        public Card[] newArray(int size) {
            return new Card[size];
        }
    };

    public String getProductName() {
        return productName;
    }

    public String getDescription() {
        return description;
    }

    public List<Price> getPrices() {
        return prices;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(productName);
        dest.writeString(description);
        dest.writeTypedList(prices);
    } }

意图(片段内部):

Intent intent = new Intent(getActivity(), Activity2.class);
                        intent.putExtra(Activity2.ARG_BUNDLE, card);
                        startActivity(intent);

Activity2接收对象:

Intent intent = getIntent();
        if (intent != null) {
            bundle = intent.getParcelableExtra(ARG_BUNDLE);
        }

但是Activity2只接收没有PriceList的对象卡(对象价格也实现了Parcelable)。也许我做错了什么?

2 个答案:

答案 0 :(得分:2)

你不是在阅读你的方法中的价格arraylist。它应该是:

protected Card(Parcel in) {
        productName = in.readString();
        description = in.readString();
        prices= in.createTypedArrayList(Price.CREATOR); // add this line to your code.
    }

答案 1 :(得分:1)

Intent i = getIntent();  
stock_list = i.getStringArrayListExtra("stock_list");

发送结束

 Intent intent = new Intent(this, editList.class);
        intent.putStringArrayListExtra("stock_list", stock_list);
        startActivity(intent);