How can I make my OrmLite entity a Parcelable object?

947 views
Skip to first unread message

Matt Huggins

unread,
Jun 1, 2013, 3:56:34 PM6/1/13
to ormlit...@googlegroups.com
I'd like to treat one of my entities as Parcelable.  I'm not sure how to approach parceling ForeignCollections, unfortunately.  Should I simply convert them to arrays or ArrayLists and parcel them as TypedArrays?  If I do this, how do I convert them back to ForeignCollections when I convert from a Parcel back into my entity?  Thanks!

Matt Huggins

unread,
Jun 1, 2013, 4:03:02 PM6/1/13
to ormlit...@googlegroups.com
It's also worth noting that I tried NOT parceling ForeignCollection objects, in hopes that they would automatically be requeried, but instead I ended up with a NullPointerException.

Matt Huggins

unread,
Jun 1, 2013, 9:20:48 PM6/1/13
to ormlit...@googlegroups.com
Okay, I solved this in case anyone else has the same question.  I changed all my ForeignCollection objects to Collection objects (while still maintaining the ForeignCollectionField annotations).  I also created these two methods for parceling/unparceling collections:

protected final static <T extends Entity> void parcelCollection(final Parcel out, final Collection<T> collection) {
    if (collection != null) {
        out.writeInt(collection.size());
        out.writeTypedList(new ArrayList<T>(collection));
    } else {
        out.writeInt(-1);
    }
}
protected final static <T extends Entity> Collection<T> unparcelCollection(final Parcel in, final Creator<T> creator) {
    final int size = in.readInt();
    if (size >= 0) {
        final List<T> list = new ArrayList<T>(size);
        in.readTypedList(list, creator);
        return list;
    } else {
        return null;
    }
}

I'm not sure if there are any repercussions to using a Collection instead of a ForeignCollection, but I haven't experienced any issues in my app so far. 

On Saturday, June 1, 2013 1:56:34 PM UTC-6, Matt Huggins wrote:
Reply all
Reply to author
Forward
0 new messages