Search code examples
javaandroidparcelablejava-time

Is this the right way to pass a Period class through a Parcelable


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());
}

Solution

  • 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());
    }