Java – Parceler: Unable to find read/write generator of type ForeignCollection

Parceler: Unable to find read/write generator of type ForeignCollection… here is a solution to the problem.

Parceler: Unable to find read/write generator of type ForeignCollection

I tried using ORMLite with Parceler, but Parceler found an error :

Error:(44, 36) error: Parceler: Unable to find read/write generator for type com.j256.ormlite.dao.ForeignCollection<PassKeyItem> for CategoryItem.passKeyItems

This is my object :

CategoryItem.class

@Parcel
@DatabaseTable(tableName = "categories")
public class CategoryItem {
     ...
    @ForeignCollectionField(columnName = FIELD_PASS_KEY_ITEMS)
    ForeignCollection<PassKeyItem> passKeyItems;
}

PassKeyItem.class

@Parcel
@DatabaseTable(tableName = "passkey")
public class PassKeyItem {
...
  @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = FIELD_CATEGORY_ITEM_ID)
    private CategoryItem categoryItem;
}

Solution

You need to provide a converter because Parceler doesn’t know how to serialize ForeignCollection.

Here is an example in the documentation:

@Parcel
public class Item {
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    public List<Item> itemList;
}
@Parcel public class SubItem1 extends Item {}
@Parcel public class SubItem2 extends Item {}

public class ItemListParcelConverter implements ParcelConverter<List<Item>> {
    @Override
    public void toParcel(List<Item> input, Parcel parcel) {
        if (input == null) {
            parcel.writeInt(-1);
        }
        else {
            parcel.writeInt(input.size());
            for (Item item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

@Override
    public List<Item> fromParcel(Parcel parcel) {
        int size = parcel.readInt();
        if (size < 0) return null;
        List<Item> items = new ArrayList<Item>();
        for (int i = 0; i < size; ++i) {
            items.add((Item) Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader())));
        }
        return items;
    }
}

For more information, visit https://github.com/johncarl81/parceler#custom-serialization

Related Problems and Solutions