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?
}
}
You can simply use
dest.writeValue(this.aLongObject);
this.aLongObject = (Long)in.readValue(Long.class.getClassLoader());
writeValue and readValue handle null gracefully.
Please refer to https://stackoverflow.com/a/10769887/72437
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With