[英]What am I doing wrong in this Parcelable class?
I'm trying to start a new Activity and add a custom Parcelable object to the Intent. 我正在尝试启动新的Activity并将自定义的Parcelable对象添加到Intent。 Apparently this does not work: 显然这不起作用:
Class: 类:
public class TestObject implements Parcelable{
private String mString;
private int mInt;
private List<String> mList;
public TestObject() {
this.mString = "This is a String";
this.mInt = 777;
mList = new ArrayList<String>();
for(int i=0; i<100; i++){
mList.add(String.valueOf(i));
}
}
public TestObject(Parcel in) {
setmInt(in.readInt());
setmString(in.readString());
mList = new ArrayList<String>();
in.readStringList(mList);
}
public void setmString(String mString) {
this.mString = mString;
}
public void setmInt(int mInt) {
this.mInt = mInt;
}
public String getmString() {
return mString;
}
public int getmInt() {
return mInt;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mString);
dest.writeInt(mInt);
dest.writeStringList(mList);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public TestObject createFromParcel(Parcel in) {
return new TestObject(in);
}
public TestObject[] newArray(int size) {
return new TestObject[size];
}
};
} }
FirstActivity: FirstActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestObject object = new TestObject();
Intent i = new Intent(this, SecondActivity.class);
Debug.startMethodTracing("parcelable");
i.putExtra("object", object);
startActivity(i);
}
Second Activity: 第二项活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
TestObject ob = (TestObject) i.getParcelableExtra("object");
Debug.stopMethodTracing();
Log.d("object string", "string: " + ob.getmString());
}
The problem is with the List<String>
... 问题出在List<String>
...
The problem is that you write the variables to the Parcel in a different order than you read them. 问题在于,您以与读取变量不同的顺序将变量写入包裹。 You write mString first but read mInt first. 您先写mString但先读mInt。 This will work: 这将起作用:
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mString);
dest.writeInt(mInt);
dest.writeStringList(mList);
}
public TestObject(Parcel in) {
setmString(in.readString());
setmInt(in.readInt());
mList = new ArrayList<String>();
in.readStringList(mList);
}
And btw don't use a raw type for the CREATOR, use this instead: 而且顺便说一句,不要为CREATOR使用原始类型,而是使用以下原始类型:
public static final Parcelable.Creator<TestObject> CREATOR = new Parcelable.Creator<TestObject>() {
public TestObject createFromParcel(Parcel in) {
return new TestObject(in);
}
public TestObject[] newArray(int size) {
return new TestObject[size];
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.