我需要将自定义类的ArrayList从一个实体“传输”到另一个实体。我知道我需要实现Parcelable接口。
这是我的定制课。
public class cSportsList implements Parcelable {
boolean checked;
String name;
cSportsList(boolean check, String name_) {
checked = check;
name = name_;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
//Non posso passare un booleano e non posso fare il cast boolean -> int
if (checked) {
dest.writeInt(1);
}
else dest.writeInt(0);
dest.writeString(name);
}
public static final Parcelable.Creator<cSportsList> CREATOR = new Parcelable.Creator<cSportsList>() {
public cSportsList createFromParcel(Parcel in) {
return new cSportsList(in);
}
public cSportsList[] newArray(int size) {
return new cSportsList[size];
}
};
private cSportsList(Parcel in) {
if (in.readInt() == 1) {
checked = true;
}
else {
checked = false;
}
name = in.readString();
}
}这是实体中的代码"from“
//This is sportsMap: ArrayList<cSportsList> sportsMap = new ArrayList<cSportsList>();
Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class);
intent.putParcelableArrayListExtra("sportsMap", (ArrayList<? extends Parcelable>) sportsMap); //I have tried with ArrayList<cSportsList> too.
this.startActivity(intent);这是实体"to“中的代码
final Intent srcIntent = getIntent();
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap");问题是:在实体中"To“sportsMap是空的。如果我在"writeToParcel“和"cSportsList(Parcelable )”函数中设置了“断点”,我会看到这两个函数都执行了代码。
我的错误在哪里?
谢谢。M.
发布于 2017-03-07 11:13:33
使用以下代码
srcIntent.getParcelableArrayListExtra("sportsMap");= sportsMap
发布于 2017-03-07 09:37:47
当你阅读时你需要使用
srcIntent.getParcelableArrayListExtra("sportsMap");在下面的代码中使用
intent.putParcelableArrayListExtra("sportsMap", sportsMap);若要从意图中阅读,请使用
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");在Pass ArrayList to Activity上阅读类似的解决方案
发布于 2017-03-07 09:41:23
你应该使用:
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");https://stackoverflow.com/questions/42644631
复制相似问题