0

I have a class that implements a Parcelable, but it had only primitive types as members.

Until now, I passed an instance of this class as a Parcelable without problem between two activities.

But I'm adding a member which type is a Period (java.time).

Doing my research on internet I found that passing a member object (not parcelable) of a class that implements a parcelable, I should pass actually the fields of this object (primitive types or String) through the parcelable and not the whole object (since it's not implementing the parcelable)

Looking at the documentation, the Period class doesn't implement Parcelable.

So, would be this the right way to pass it through a Parcelable?

Period objPeriod;

public void writeToParcel(Parcel out, int flags){
    out.writeString(objPeriod.toString());
}

private MyClass(Parcel in){
    objParcel.parse(in.readString());
}
tdmsoares
  • 533
  • 7
  • 24
  • 1
    I think you should pass the results of `Period.getYears()`, `Period.getMonths()` and `Period.getDays()` as `int`s and recreate it in the destination `Activity` using those values like `Period.of(years, months, days);`, but haven't done that so far... So I don't know for sure if that's a neat solution. – deHaar Jul 01 '20 at 14:08

1 Answers1

2

Period implements Serializable, so you can just write it that way.

public void writeToParcel(Parcel out, int flags) {
  out.writeSerializable(objPeriod);
}

private MyClass(Parcel in) {
  objPeriod = (Period) in.readSerializable();
}

However, it is best to avoid Serializable if possible. Given that the Javadoc for Period specifically does define a structured toString() implementation that can then be parsed back:

Outputs this period as a String, such as P6Y3M1D.

Then I think your original suggestion should be perfectly acceptable, using the static Period.parse() method:

Obtains a Period from a text string such as PnYnMnD.

This will parse the string produced by toString() which is based on the ISO-8601 period formats PnYnMnD and PnW.

public void writeToParcel(Parcel out, int flags) {
  out.writeString(objPeriod.toString());
}

private MyClass(Parcel in) {
  objPeriod = Period.parse(in.readString());
}
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • In fact I was in doubt between using Serializable (more easy) and other methods like the `objPeriod.toString()` and `Period.parse(in.readString())`. I always hear to avoid Serializable in Android because of Performance impact but I was in doubt because Period Class is Serializable... So I wonder, why the android implementation of this class still keep as Serializable, if it's a bad practice to use it? A compatibiliy with the original Java implementation? – tdmsoares Jul 01 '20 at 14:45
  • 1
    `Parcelable` is specific to the Android framework, while `Period` is part of the `java.time` library as part of the Java framework. – Kevin Coppock Jul 01 '20 at 14:48