我想通过使用list object
和Parcelable
来传递Intent
,但是遇到一个问题:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable
我的Contact.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);
我该如何解决? 非常感谢
答案 0 :(得分:3)
Use putParcelableArrayList instead of putParcelable.
bundle.putParcelableArrayList("CONTACT_ARRAY_LIST", mData); // Be sure "mData" is not null here
答案 1 :(得分:2)
ArrayList
不可包裹,因为错误明确指出。但是它是可序列化的as documented,所以就这样走吧:
bundle.putSerializable("CONTACT_ARRAY_LIST", mData);
或者您可以使用putParcelableArrayList()
:
bundle.putParcelableArrayList("CONTACT_ARRAY_LIST", mData);