在活动之间传递Parcelable项目

时间:2013-08-20 05:41:02

标签: android android-intent parcelable

我无法通过Intent传递对象。我一直得到一个空指针错误。这是:

在我的ListActivity中:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Intent intent = new Intent(MyListActivity.this, DetailsActivity.class);
    intent.putExtra("this_item", my_array.get(position));
    startActivity(intent);
}

在DetailsActivity类的onCreate()中:

thisItem = (MyObject) getIntent().getExtras().getParcelable("this_item");
System.err.println(thisItem.getDescription()); //<--Null pointer error!

MyObject类确实实现了Parcelable。为什么我不能通过这个对象?我糊涂了。谢谢你的帮助。

编辑:这是班级:

public class MyObject implements Comparable<MyObject>, Parcelable {

    private Date date;
    private MyType my_type;
    private String description;
    private int flags;

    public MyObject(Date date, MyType type, String desc) {
        this.date = date;
        this.my_type = type;
        this.description = desc;
    }

    public Date getDate() {return date;}
    public MyType getMyType() {return my_type;}
    public String getDescription() {return description;}

    public int compareTo(MyObject another) {
        if (getDate() == null || another.getDate() == null) {return 0;}
        return getDate().compareTo(another.getDate());
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(flags);
    }   

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

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

    private MyObject (Parcel in) {
        flags = in.readInt();
    }
}

1 个答案:

答案 0 :(得分:2)

如果你想通过意图将数据从一个活动传递到另一个活动,那么对象必须在android中可以是可分区的或可序列化的。对于parcelable,你必须实现可序列化的接口。对于parcelable,你必须实现parcelable接口.. < / p>

像这样编写parcelable类.. parcel example