将序列化置于意图不起作用

时间:2017-07-26 10:17:47

标签: android

我用下面的代码放入了我的对象(放置列表确实存在,我检查了调试器)

Intent intent = new Intent(getApplicationContext(), ProductActivity.class);
intent.putExtra("product", CategoryActivity.this.list.get(position));
                    startActivity(intent);

然后回复

Intent intent = getIntent();
product = (Product) intent.getSerializableExtra("product");

但它是空的

模型类正在关注

public class Product implements Serializable {

    Integer pk;
    String name;
    String description;
    Integer price;
    String image_url;
    List<Option> options;

    public Product(Integer pk, String name, String description, Integer price, String image_url, List<Option> options) {
        this.pk = pk;
        this.name = name;
        this.description = description;
        this.price = price;
        this.image_url = image_url;
        this.options = options;
    }

    public Integer getPk() {
        return pk;
    }

    public void setPk(Integer pk) {
        this.pk = pk;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }

    public List<Option> getOptions() {
        return options;
    }

    public void setOptions(List<Option> options) {
        this.options = options;
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您必须添加更多代码才能在意图数据中使用您的类。

        import android.os.Parcel;
        import android.os.Parcelable;

        public class Yourclass implements Parcelable {
        //your code

        @Override
        public void writeToParcel(Parcel out, int flags) {
        //e.g.
            out.writeInt(this.getWhat());
        //similar code
        }

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


    private YourClass(Parcel in) {
    //e.g.
        this.setWhat(in.readInt());
        }

public static final Parcelable.Creator<YourClass> CREATOR
= new Parcelable.Creator<YourClass>() {

public YourClass createFromParcel(Parcel in) {
        return new YourClass(in);
    }

public YourClass[] newArray(int size) {
        return new YourClass[size];
    }
};
        }

存储使用intent.putExtra(EXTRANAME, obj);以检索使用YourClass myObj = (YourClass) getIntent().getParcelableExtra(EXTRANAME);