如何为包含List<List<String>>的类实现Parcelable?

9

除了List<List<String>>之外,我的Parcelable类的所有字段都有可工作的实现。

class Employee implements Parcelable {

    List<List<String>> details;
    //.......

    protected Employee(Parcel in) {
        details = new ArrayList<List<String>>();
        // i know this is wrong just posting to clarify
        in.readList(details, List.class.getClassLoader());
        //......
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeList(details);
        //.....
    }

    public int describeContents() {
        return 0;
    }

    public static final Parcelable.Creator<Employee> CREATOR = 
            new Parcelable.Creator<Employee>() {
        public Employee createFromParcel(Parcel in) {
            return new Employee(in);
        }

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

}

异常:

05-10 19:07:44.072: E/AndroidRuntime(10661): Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@42a509e8: Unmarshalling unknown type code 3604535 at offset 268
3个回答

8

对我来说,扩展 ArrayList 并在其上实现 Parcelable 是有效的。

public class ParcelableArrayList extends ArrayList<String> implements 
        Parcelable {

    private static final long serialVersionUID = -8516873361351845306L;

    public ParcelableArrayList(){
        super();
    }

    protected ParcelableArrayList(Parcel in) {
        in.readList(this, String.class.getClassLoader());
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeList(this);
    }   

    public static final Parcelable.Creator<ParcelableArrayList> CREATOR = 
            new Parcelable.Creator<ParcelableArrayList>() {
        public ParcelableArrayList createFromParcel(Parcel in) {
            return new ParcelableArrayList(in);
        }

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

}

以及员工类

class Employee implements Parcelable {

    List<ParcelableArrayList> details;
    //.......

    protected Employee(Parcel in) {
        details = new ArrayList<ParcelableArrayList>();
        in.readTypedList(details,ParcelableArrayList.CREATOR);
        //......
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeList(details);
        //.....
    }

    public int describeContents() {
        return 0;
    }

    public static final Parcelable.Creator<Employee> CREATOR = 
            new Parcelable.Creator<Employee>() {
        public Employee createFromParcel(Parcel in) {
            return new Employee(in);
        }

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

}

0
我会创建一个继承自List的类,并在该类上实现Parcelable。你可以将其视为普通列表,但允许它可被打包。

0
创建一个实现 Parcelable 接口的 DetailsEntry 类,它包含 List,并在 Employee 类中使用 List details。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接