gpt4 book ai didi

android - 如何使具有嵌套对象的类 Parcelable

转载 作者:IT老高 更新时间:2023-10-28 21:47:58 24 4
gpt4 key购买 nike

我想让 A 类 Parcelable。

public class A {
public String str;
public ArrayList<B> list;
}

这是我到目前为止所想出的。但是它会因 NullPointerException 而崩溃。问题在于这两个语句:dest.writeList(list); & in.readList(list, this.getClass().getClassLoader());。我不知道从这里做什么:(

A 类

public class A implements Parcelable {
public String str;
public ArrayList<B> list;

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(str);
dest.writeList(list);
}

private A(Parcel in) {
str = in.readString();
in.readList(list, this.getClass().getClassLoader());
}

public static final Parcelable.Creator<A> CREATOR
= new Parcelable.Creator<A>() {
public A createFromParcel(Parcel in) {
return new A(in);
}

public A[] newArray(int size) {
return new A[size];
}
};
}

B 类

public class B implements Parcelable {
public String str;

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(str);
}

private B(Parcel in) {
str = in.readString();
}

public static final Parcelable.Creator<B> CREATOR
= new Parcelable.Creator<B>() {
public B createFromParcel(Parcel in) {
return new B(in);
}

public B[] newArray(int size) {
return new B[size];
}
};
}

感谢您的宝贵时间。

最佳答案

我终于知道要在 Google 中输入什么了 :),然后找到了 Android, How to use readTypedList method correctly in a Parcelable class?

解决方案是改用 read-/writeTypedList。我还初始化了 arraylist 以避免任何进一步的 NullPointerException。

A 类

public class A implements Parcelable {
public String str;
public ArrayList<B> list = new ArrayList<B>();

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(str);
dest.writeTypedList(list);
}

private A(Parcel in) {
str = in.readString();
in.readTypedList(list, B.CREATOR);
}

public static final Parcelable.Creator<A> CREATOR
= new Parcelable.Creator<A>() {
public A createFromParcel(Parcel in) {
return new A(in);
}

public A[] newArray(int size) {
return new A[size];
}
};
}

B 类

public class B implements Parcelable {
public String str;

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(str);
}

private B(Parcel in) {
str = in.readString();
}

public static final Parcelable.Creator<B> CREATOR
= new Parcelable.Creator<B>() {
public B createFromParcel(Parcel in) {
return new B(in);
}

public B[] newArray(int size) {
return new B[size];
}
};
}

关于android - 如何使具有嵌套对象的类 Parcelable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14178736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com