I am working on an android project and trying to make use of Parcelable so I can parse the class object in a bundle to another activity.
Below is my 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];
}
};
}
I have ArrayList<GroupAndItems> groupAndItemsList
which I put into the bundle and the intent as follows
bundle = new Bundle();
bundle.putParcelableArrayList("groupsAndItems", groupAndItemsList);
Intent intent = new Intent(getContext(), GroupedSpinnerItems.class);
intent.putExtras(bundle);
getContext().startActivity(intent);
In the activty where I pass the parcelable class in, I retrieve it using the following:
bundle = getIntent().getExtras();
if (bundle != null)
{
ArrayList<GroupAndItems> groupAndItems = bundle.getParcelableArrayList("groupsAndItems");
}
I am then getting the following exception
java.lang.RuntimeException: Parcel android.os.Parcel@5620ba2: Unmarshalling unknown type code 7143525 at offset 176
which is on the line
in.readList(this.items, null);
in the constructor of my parcelable class that has Parcel in
as the parameter.
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);
}
You first read String in GroupAndItems(Parcel in)
but you first write List in writeToParcel(Parcel parcel, int i)
you must do that in same order all time for example if you write String then List you should read String then List