Search code examples
javaandroidlistparcelableparcel

write two lists of parcelables into parcel in Android


I have object Contact:

public class Contact implements Parcelable

with properties:

private List<EmailAttribute> contact_emails_attributes = new ArrayList<EmailAttribute>();
private List<PhoneAttribute> contact_phones_attributes = new ArrayList<PhoneAttribute>();

EmailAttribute and PhoneAttribute implemets Parcelable.

How to write contact's properties into parcel and read them ? I was looking for solution long time but I have found no solution how to write different parcelables into parcel. Thanks.


Solution

  • You can do it by using the methods Parcel.writeTypedList(List) and Parcel.readTypedList(List, Creator) like this:

    Read it from the Parcel:

    public Contact(Parcel in){
       contact_emails_attributes = in.readTypedList(contact_emails_attributes, EmailAttribute.CREATOR);
       contact_phones_attributes = in.readTypedList(contact_phones_attributes, PhoneAttribute.CREATOR);
    }
    

    Write it to the Parcel:

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeTypedList(contact_emails_attributes); 
        dest.writeTypedList(contact_phones_attributes);
    }