使用Parcelable和Intent在两个活动之间传递ArrayList

时间:2012-07-29 19:16:19

标签: java android android-intent arraylist parcelable

目前我遇到了将ArrayList<MyClass>从一个活动传递到另一个活动的问题。我试图在MyClass中实现Parcelable并在活动中使用intent但似乎我做错了。当我使用startActivity intent调用应用程序的窗口冻结时,我收到错误“!!!失败的Bender Transaction !!!”。我在这里和其他一些地方读到,交易的大小可能会导致错误。 MyClass拥有一张图片。在调用startActivity的那一刻,ArrayList包含五个元素,每个元素都有一个位图。所有图像的大小都在70kb以下。

这是我的实际代码:

public class MyClass implements Parcelable {

public enum Type {
    VIDEO, AUDIO
}

private int id;
private String name;
private String url;
private double longitude;
private double latitude;
private double gpsDistance;
private String description;
private String thumb;
private Bitmap thumbpic;
private Type type;

public MyClass() {
    this.gpsDistance = 0;
}

public MyClass(Parcel in) {
    readFromParcel(in);
}

/* Setter & Getter */


public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(name);
    dest.writeString(url);
    dest.writeDouble(longitude);
    dest.writeDouble(latitude);
    dest.writeDouble(gpsDistance);
    dest.writeString(description);
    dest.writeString(thumb);
    dest.writeParcelable(thumbpic, flags);
    dest.writeString((type == null) ? "" : type.name());

}



private void readFromParcel(Parcel in) {
    this.id = in.readInt();
    this.name = in.readString();
    this.url = in.readString();
    this.longitude = in.readDouble();
    this.latitude = in.readDouble();
    this.gpsDistance = in.readDouble();
    this.description = in.readString();
    this.thumb = in.readString();
    this.thumbpic = (Bitmap) in.readParcelable(getClass().getClassLoader());
    try {
        type = Type.valueOf(in.readString());
    } catch (IllegalArgumentException x) {
        type = null;
    }
}

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

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

活动中的一些代码段(MainActivity)启动第二个(ListActivity

ArrayList<Content> contentElements  = new ArrayList<Content>();

Intent intent = new Intent(MainActivity.this,ListActivity.class);

intent.putParcelableArrayListExtra("content", contentElements);

ListActivity

中的处理
Intent i = getIntent();
contentElements= i.getParcelableArrayListExtra("content");

有人知道导致此问题的原因并有解决方案或替代方法吗?

非常感谢!

0 个答案:

没有答案