3

If say I have following with a long object. Does below example demonstrate correct way of reading and writing Long object?

Class MyClass implements Parcelable {
   private Long aLongObject;

    public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
    @Override
    public MyClass createFromParcel(Parcel in) {
        return new MyClass(in);
    }

    @Override
    public MyClass[] newArray(int size) {
       .....
    }
};


protected MyClass(Parcel in) {// reading Parcel
    super(in);

  aLongObject = in.readLong(); // correct way to ready Long object?
 }

   @Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
    super.writeToParcel(dest, flags);

      dest.writeLong(aLongObject); // is this correct way to send Long?
  }
}
Akshay
  • 806
  • 11
  • 26

2 Answers2

2

The problem with your approach is that a Long value may be null but the Parcel methods only take/ return values of the primitive data type long, see the documentation for details. So you need a workaround to store a Long value.

I like to use a int to indicate whether my Long value is null (you can only store boolean arrays no single boolean values) and a long to store the numerical value if it isn't:

Writing to the Parcel

int indicator = (aLongObject == null) ? 0 : 1;
long number = (aLongObject == null) ? 0 : aLongObject;
dest.writeInt(indicator); 
dest.writeLong(number); 

Reading from the Parcel

// NOTE: reading must be in the same order as writing
Long aLongObject;
int indicator = in.readInt();
long number = in.readLong();
if(indicator == 0){
    aLongObject = null;
}
else{
    aLongObject = number;
}
Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
  • Thanks for your answer. Quick question, is above the best approach or to use dest.writeValue and in.readValue since this is an Object? – Akshay Sep 27 '18 at 17:57
  • @Akshay - what I do not understand is why you have a `class MyClass implements Parcelable` and a Constructor for `V3MemberReward` inside. There is a nice tutorial [here](https://guides.codepath.com/android/using-parcelable) which may be helpful – Bö macht Blau Sep 27 '18 at 18:04
  • Sorry for the typo.. I have fixed that – Akshay Sep 27 '18 at 18:05
  • @Akshay - I think using the two primitive data type values to map the `Long` value is better than working with an `Object` since `Object` creation is more expensive (memory and CPU time). OTOH I doubt it will matter much on modern devices – Bö macht Blau Sep 27 '18 at 18:07
2

You can simply use

Write

dest.writeValue(this.aLongObject);

Read

this.aLongObject = (Long)in.readValue(Long.class.getClassLoader());

writeValue and readValue handle null gracefully.

Please refer to https://stackoverflow.com/a/10769887/72437

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875