我有一个叫做SuperMedia的类,它实现了Parcelable。该类的字段之一是ArrayList子级。当我创建一个Bundle并尝试将“ SuperMedia”对象从一个活动传递到另一个活动时,除ArrayList“ children”(每次都显示为空)外,所有字段都传递良好。

在我的第一个活动中,我这样做:

 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);


在第二项活动中,我做了:

  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类。

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(){

}


}

最佳答案

如果只想通过意图传递对象,则可以使SuperMedia Serializable不需要Parcelable。

public class SuperMedia implements Serializable{...}


放在

Bundle a = new Bundle(); a.putSerializable("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/

10-12 22:37