我有一个名为 SuperMedia 的类,它实现了 Parcelable。该类的字段之一是 ArrayList 子项。当我创建一个 Bundle 并尝试将“SuperMedia”对象从一个 Activity 传递到另一个 Activity 时,所有字段都可以正常传递,但 ArrayList“子项”除外,它每次都显示为空。
在我的第一个 Activity 中,我这样做:
Bundle a = new Bundle();
a.putParcelable("media",media); //media is an object of type "SuperMedia" and all the "children" have been initialized and added to the array
final Intent i = new Intent("com.tv.video.subcategories");
i.putExtra("subcategories", a);
在我的第二项 Activity 中,我会:
Intent i = getIntent();
Bundle secondBun = i.getBundleExtra("subcategories");
SuperMedia media = secondBun.getParcelable("media"); //For some reason the ArrayList"children" field shows up as empty.
我不确定为什么会发生这种情况。如果有人能指导我走上正确的道路,我将不胜感激。顺便说一句,下面是我的 SuperMedia 类(class)。
public class SuperMedia implements Parcelable{
public URI mthumb;
public String mTitle;
public ArrayList<SuperMedia> children = new ArrayList();
public SuperMedia(URI thumb, String title) {
this.mthumb = thumb;
this.mTitle = title;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(mTitle);
dest.writeString(mthumb.toString());
dest.writeTypedList(children);
}
public static final Parcelable.Creator<SuperMedia> CREATOR = new Parcelable.Creator<SuperMedia>() {
public SuperMedia createFromParcel(Parcel in) {
return new SuperMedia(in);
}
public SuperMedia[] newArray(int size) {
return new SuperMedia[size];
}
};
private SuperMedia(Parcel in) {
mTitle = in.readString();
try {
mthumb = new URI(in.readString());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.readTypedList(children, SuperMedia.CREATOR);
}
public SuperMedia(){
}
}
最佳答案
如果您只想通过 Intent 传递对象,那么您可以使 SuperMedia Serialized 无需 Parcelable。
public class SuperMedia implements Serializable{...}
把它写成
bundle a = new Bundle();
a.putSerialized("media",media);
我们得到它。
Intent i = getIntent();
Bundle secondBun = i.getBundleExtra("subcategories");
SuperMedia media = (SuperMedia)secondBun.getSerializable("media");
如果您确实需要 Parcelable 那么它可能会帮助您。 Arraylist in parcelable object
关于java - 读取 Parcelable 中的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549993/