java - 读取 Parcelable 中的 ArrayList

标签 java android arraylist parcelable

我有一个名为 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/

相关文章:

java - 如何使用 AsynchronousServerSocketChannel 绑定(bind)多个端口?

java - 验证响应中特定 JSON 对象的 json 模式

java - 动态数组斐波那契

java - 查找数组列表中的重复元素

java - 使用 jdbc 从数据库中按列检索值

android - 如何在没有触摸屏的情况下显示android状态栏?

android - 如何在 flexbox-layout 中改变项目的方向

Android - 如何结合按钮的形状可绘制和文本颜色不同状态?

java - java中字符串数组数组的数据结构

java - 数组列表java程序