如果说我有一个很长的话。下面的示例是否演示了读写Long对象的正确方法?
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?
}
}
答案 0 :(得分:2)
您可以简单地使用
dest.writeValue(this.aLongObject);
this.aLongObject = (Long)in.readValue(Long.class.getClassLoader());
writeValue
和readValue
优雅地处理null
。
答案 1 :(得分:1)
您的方法存在的问题是Long
的值可能是null
,但是Parcel
方法仅采用/返回原始数据类型long
的值,请参见documentation了解详情。因此,您需要一种解决方法来存储一个Long
值。
我喜欢使用int
来指示我的Long
值是否为null
(您只能存储boolean
数组,而不能存储单个boolean
值),并且long
用于存储数字值,如果不是的话:
写给Parcel
int indicator = (aLongObject == null) ? 0 : 1;
long number = (aLongObject == null) ? 0 : aLongObject;
dest.writeInt(indicator);
dest.writeLong(number);
从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;
}