请问如何解决这个问题?
Parcelable接口i在客户pojo对象中实现。请告诉我如何在活动2中读取客户对象?
Customer.java
public Customer implements Parcelable{
private String name;
private String phone;
private List<AccountDetails> accoutDetails;
/getter and setters
public int describeContents() {
return 0;
}
public Customer(Parcel in) {
name= in.readString();
phone= in.readString();
accoutDetails= new ArrayList<AccountDetails>();
in.readList(accoutDetails,null);
}
public static final Parcelable.Creator<Customer> CREATOR = new Parcelable.Creator<Customer>() {
public Customer createFromParcel(Parcel in) {
return new Customer(in);
}
public Customer[] newArray(int size) {
return new Customer[size];
}
};
@Override
public void writeToParcel(Parcel dest, int arg1) {
// TODO Auto-generated method stub
dest.writeString(this. name);
dest.writeString(this.phone);
dest.writeList(accoutDetails);
}
}
在活动1中使用如下代码:
Customer selected_row=(Customer) parent.getAdapter().getItem(position);
Intent intent = new Intent(getApplicationContext(), Activity2.class);
Bundle bundle = new Bundle();
bundle.putParcelable("selected_customer", selected_row);
intent.putExtras(bundle);
startActivity(intent);
活动2: Customer cust_object = getBundle.getParcelable("selected_customer");
java.lang.RuntimeException: Parcel android.os.Parcel@1219dd0f: Unmarshalling unknown type code 6881396 at offset 660
at android.os.Parcel.readValue(Parcel.java:2228)
at android.os.Parcel.readListInternal(Parcel.java:2526)
at android.os.Parcel.readList(Parcel.java:1661)
请告诉我如何在活动2中读取客户对象
虽然支持序列化,但不建议用于Android。请看这篇文章。
我认为你的问题在这行代码上:
in.readList(accoutDetails,null);
因为accountDetails是一个自定义accountDetails对象的列表,你需要accountDetails也实现Parcelable。
这样做,然后将上面的代码行改为:
in.readTypedList(accoutDetails, AccountDetails.CREATOR);
编辑1
同时,改变:
public Customer(Parcel in) {
name= in.readString();
phone= in.readString();
accoutDetails= new ArrayList<AccountDetails>();
in.readTypedList(accoutDetails,null);
}
:
public Customer(Parcel in) {
name= in.readString();
phone= in.readString();
in.readTypedList(accoutDetails, AccountDetails.CREATOR);
}
和变化:
@Override
public void writeToParcel(Parcel dest, int arg1) {
// TODO Auto-generated method stub
dest.writeString(this. name);
dest.writeString(this.phone);
dest.writeList(accoutDetails);
}
:
@Override
public void writeToParcel(Parcel dest, int arg1) {
dest.writeString(this.name);
dest.writeString(this.phone);
dest.writeTypedList(accoutDetails);
}
编辑2
public Customer implements Parcelable{
private String name;
private String phone;
private List<AccountDetails> accoutDetails = new ArrayList<AccountDetails>();