Parcelable class 抛出运行时异常解组未知类型

Parcelable class throwing runtime exception unmarshalling unknown type

我正在开发一个 android 项目并尝试使用 Parcelable,这样我就可以将捆绑包中的 class 对象解析为另一个 activity。

下面是我的class

public class GroupAndItems implements Parcelable
{


    public String group;
    public List<String> items;

    public GroupAndItems(String group, List<String> items)
    {
        this.group = group;
        this.items = items;
    }

    public GroupAndItems(Parcel in)
    {
        this.group = in.readString();
        this.items = new ArrayList<>();
        in.readList(this.items, null);
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeList(items);
        parcel.writeString(group);
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator<GroupAndItems>() {

        @Override
        public GroupAndItems createFromParcel(Parcel parcel) {
            return new GroupAndItems(parcel);
        }

        @Override
        public GroupAndItems[] newArray(int i) {
            return new GroupAndItems[i];
        }
    };
}

我有 ArrayList<GroupAndItems> groupAndItemsList 放入捆绑包中,意图如下

bundle = new Bundle();
bundle.putParcelableArrayList("groupsAndItems", groupAndItemsList);

Intent intent = new Intent(getContext(), GroupedSpinnerItems.class);
intent.putExtras(bundle);
getContext().startActivity(intent);

在我传递 parcelable class 的活动中,我使用以下方法检索它:

bundle = getIntent().getExtras();
        if (bundle != null)
        {
ArrayList<GroupAndItems> groupAndItems = bundle.getParcelableArrayList("groupsAndItems");
        }

然后我收到以下异常

java.lang.RuntimeException: Parcel android.os.Parcel@5620ba2: Unmarshalling unknown type code 7143525 at offset 176

即上线

in.readList(this.items, null); 在我的 parcelable class 的构造函数中,它以 Parcel in 作为参数。

public GroupAndItems(Parcel in)
    {

        this.items = new ArrayList<>();
        in.readList(this.items, null);
        this.group = in.readString();
    }

@Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeList(items);
        parcel.writeString(group);
    }

您首先在 GroupAndItems(Parcel in) 中读取字符串,但您首先在 writeToParcel(Parcel parcel, int i) 中写入列表,您必须始终以相同的顺序执行此操作,例如,如果您先写入字符串,然后再写入列表,那么您应该先读取字符串,然后再读取列表