I'm working with Parcelable class. How can I read and write java.util.Date
object to and from this class?
Parcelable is the Android implementation of Java serializable. Parcelable is relatively fast as compared to the java serialization. It's recommended to use Parcelable.
We need some Context! Creating a Parcelable class is a vital skill for Android Developers because it allows you to pass an object from one Activity to another. This series will walk you through step by step in the process of implementing a parcelable class and using it in a simple App.
A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.
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()); }
In Kotlin we may create extension for Parcel - the simplest solution.
fun Parcel.writeDate(date: Date?) { writeLong(date?.time ?: -1) } fun Parcel.readDate(): Date? { val long = readLong() return if (long != -1L) Date(long) else null }
And use it
parcel.writeDate(date) parcel.readDate()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With