我正在尝试将自定义对象从一项活动传递到另一项活动。 我发现我们可以使用捆绑包将数据传递到意图中,并且需要在类中实现可打包的接口。
在以下代码中,我删除了无用的东西。
django.contrib.auth.middleware.AuthenticationMiddleware
在此类中,我有另一个自定义对象的列表:
public class TravelCard implements Parcelable {
public static final Creator<TravelCard> CREATOR = new Creator<TravelCard>() {
@Override
public TravelCard createFromParcel(Parcel in) {
return new TravelCard(in);
}
@Override
public TravelCard[] newArray(int size) {
return new TravelCard[size];
}
};
private String travelTitle, travelCountry, dateRange, numOfPerson;
private List<TravelDay> days;
protected TravelCard(Parcel in) {
travelTitle = in.readString();
travelCountry = in.readString();
dateRange = in.readString();
numOfPerson = in.readString();
in.readTypedList(days, TravelDay.CREATOR);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.travelTitle);
dest.writeString(this.travelCountry);
dest.writeString(this.dateRange);
dest.writeString(this.numOfPerson);
dest.writeTypedList(this.days);
}
我认为直到现在一切都应该没事。
在我的活动中:
public class TravelDay implements Parcelable {
public static final Creator<TravelDay> CREATOR = new Creator<TravelDay>() {
@Override
public TravelDay createFromParcel(Parcel in) {
return new TravelDay(in);
}
@Override
public TravelDay[] newArray(int size) {
return new TravelDay[size];
}
};
public int current_day;
private String title, note, dateOfToday;
protected TravelDay(Parcel in) {
title = in.readString();
note = in.readString();
dateOfToday = in.readString();
current_day = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(note);
dest.writeString(dateOfToday);
dest.writeInt(current_day);
}
然后在TravelDayActivity中:
Intent intent = new Intent(MainActivity.this, TravelDayActivity.class);
Bundle data = new Bundle();
data.putParcelable(DataKey.TRAVEL_CARD_BUNDLE,item);
intent.putExtras(data);
startActivity(intent);
每次我尝试访问TravelDayActivity时,应用都会停止运行。 我使用调试模式搜索了错误的内容,但是没有找到任何内容。 预先谢谢你
编辑: 在MainActivity中,这就是获取项目变量的方式:
Intent intent = getIntent();
Bundle data = intent.getExtras();
TravelCard travelCard = data.getParcelable(DataKey.TRAVEL_CARD_BUNDLE);
每当我单击一个回收站视图项目之一时,就会执行上面的代码。