在Android Parcelable类中读写长对象

时间:2018-09-27 17:42:33

标签: android object long-integer parcelable

如果说我有一个很长的话。下面的示例是否演示了读写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?
  }
}

2 个答案:

答案 0 :(得分:2)

您可以简单地使用

dest.writeValue(this.aLongObject);

阅读

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

writeValuereadValue优雅地处理null

请参阅https://stackoverflow.com/a/10769887/72437

答案 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;
}