请帮我解决这个问题?
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中的客户对象?
答案 0 :(得分:0)
虽然支持序列化,但不建议用于Android。请参阅示例this post。
我认为你的问题出在这行代码上:
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>();