Reading and writing java.util.Date from Parcelable class
android, java
Solution
Use writeSerializable where Date is Serializable. (But not a good idea. See below for another better way)
@Override
public void writeToParcel(Parcel out, int flags) {
// Write object
out.writeSerializable(date_object);
}
private void readFromParcel(Parcel in) {
// Read object
date_object = (java.util.Date) in.readSerializable();
}
But Serializing operations consume much performance. How can overcome this?
So better use is to convert date into Long while writing, and read Long and pass to Date constructor to get Date. See below code
@Override
public void writeToParcel(Parcel out, int flags) {
// Write long value of Date
out.writeLong(date_object.getTime());
}
private void readFromParcel(Parcel in) {
// Read Long value and convert to date
date_object = new Date(in.readLong());
}
Problem
I'm working with Parcelable class. How can I read and write `java.util.Date` object to and from this class?