Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing java.util.Date from Parcelable class

Tags:

java

android

I'm working with Parcelable class. How can I read and write java.util.Date object to and from this class?

like image 427
Mesut Avatar asked Jan 09 '14 10:01

Mesut


People also ask

Can we use Parcelable in Java?

Parcelable is the Android implementation of Java serializable. Parcelable is relatively fast as compared to the java serialization. It's recommended to use Parcelable.

What is Parcelable class in Java?

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.

What is Parcelable data?

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.


2 Answers

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());      } 
like image 85
Pankaj Kumar Avatar answered Sep 18 '22 13:09

Pankaj Kumar


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() 
like image 40
Pavel Shorokhov Avatar answered Sep 18 '22 13:09

Pavel Shorokhov