Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Write Long Object in Android Parcelable Class

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?
  }
}
like image 522
Akshay Avatar asked Jun 11 '26 05:06

Akshay


2 Answers

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

like image 84
Cheok Yan Cheng Avatar answered Jun 13 '26 17:06

Cheok Yan Cheng


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;
}
like image 31
Bö macht Blau Avatar answered Jun 13 '26 17:06

Bö macht Blau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!