首页 > 解决方案 > 尝试使用 Parcelable 传递列表对象时出错

问题描述

我想list object通过使用ParcelableIntent但我遇到了一个问题:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable

我的联系人.java:

public class Contact implements Parcelable {
    private String id;
    private String Name;
    private String Fname;
    private String Phone;
    private String Email;


    public Contact(String id, String Name, String Fname, String Phone, String Email) {
        this.id = id;
        this.Name = Name;
        this.Fname = Fname;
        this.Email = Email;
        this.Phone = Phone;
    }

    public Contact(Parcel in) {
        this.id = in.readString();
        this.Name = in.readString();
        this.Fname = in.readString();
        this.Email = in.readString();
        this.Phone = in.readString();
    }

    //Getter
    public String getId() { return id; }

    public String getName() {
        return Name;
    }

    public String getFname() {
        return Fname;
    }

    public String getEmail() {
        return Email;
    }

    public String getPhone() {
        return Phone;
    }

    //Setter

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

    public void setFname(String fname) {
        Fname = fname;
    }

    public void setEmail(String email) {
        Email = email;
    }

    public void setPhone(String phone){ Phone = phone; }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(Name);
        dest.writeString(Fname);
        dest.writeString(Phone);
        dest.writeString(Email);

    }
    public static final Parcelable.Creator<Contact> CREATOR = new Parcelable.Creator<Contact>() {
        public Contact createFromParcel(Parcel in)
        {
            return new Contact(in);
        }
        public Contact[] newArray(int size)
        {
            return new Contact[size];
        }
    };
}

我的Intent

List<Contact> mData = new ArrayList<Contact>();
Intent intent = new Intent(mContext, NewContactActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("CONTACT_ARRAY_LIST", mData);
intent.putExtras(bundle);
mContext.startActivity(intent);

我该如何解决这个问题?非常感谢  

标签: androidbundleparcelable

解决方案


Use putParcelableArrayList instead of putParcelable.
bundle.putParcelableArrayList("CONTACT_ARRAY_LIST", mData); // Be sure "mData" is not null here

推荐阅读