如果对象中的list有可能为空,如何Parcelable序列化
时间: 2024-02-01 19:13:34 浏览: 23
如果对象中的list有可能为空,可以在实现Parcelable接口的类中添加一个构造函数来处理这种情况。在构造函数中,你可以检查list是否为空,如果为空,则为其分配一个空的ArrayList对象。这样,即使对象中的list为空,也可以进行序列化和反序列化操作。
以下是示例代码:
```java
public class MyParcelable implements Parcelable {
private List<String> myList;
public MyParcelable(List<String> myList) {
if (myList == null) {
this.myList = new ArrayList<>();
} else {
this.myList = myList;
}
}
// 省略其他实现Parcelable接口的方法
public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() {
@Override
public MyParcelable createFromParcel(Parcel in) {
List<String> myList = new ArrayList<>();
in.readList(myList, null); // 注意第二个参数不能为this.getClass().getClassLoader(),否则可能会抛出空指针异常
return new MyParcelable(myList);
}
@Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
```
在上面的示例代码中,我们在构造函数中检查了list是否为空,并为其分配了一个空的ArrayList对象。在CREATOR中的createFromParcel方法中,我们使用了readList方法来读取list对象,并在构造函数中传递该对象。注意,第二个参数为null,而不是this.getClass().getClassLoader(),因为在某些情况下,this.getClass().getClassLoader()可能为空。