Search code examples
androiddateserializationparcelableparcel

How to read/write a List<Date> to a Parcel?


I have a class that implements Parcelable. What's the best way to read/write a List of Date objects to a Parcel?

This is how you can do it for a single Date object:

    date = new Date(parcel.readLong()); //read

    parcel.writeLong(date.getTime());   //write

But how to do it for a List<Date>?

I suppose the ham-fisted way of doing the write would be to loop through all Date objects and construct a long[], like so:

long[] datesAsLongs = new long[dates.size()];
for (int i = 0; i < dates.size(); i++)
    datesAsLongs[i] = dates.get(i).getTime();
parcel.writeLongArray(datesAsLongs);

And to read, you could do:

dates = new ArrayList<Date>();
for (long dateAsLong : parcel.createLongArray())
    dates.add(new Date(dateAsLong));

But I was hoping there would be something better...


Solution

  • Since Date is a Serializable object you should be able to use writeList():

    List<Date> list = new ArrayList<Date>();
    parcel.writeList(list);
    

    ArrayList also implements Serializable so you might be able to use writeValue():

    List<Date> list = new ArrayList<Date>();
    parcel.writeValue(list);    
    

    Worst case you can use writeSerializable()