我在Parcelable课程中做错了什么?

时间:2013-04-24 14:52:10

标签: android parcelable

我正在尝试启动一个新的Activity并向Intent添加一个自定义的Parcelable对象。 显然这不起作用:

类别:

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:

@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);
}

第二项活动:

@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());

}

问题在于List<String> ...

1 个答案:

答案 0 :(得分:4)

问题是您以不同于读取它的顺序将变量写入Parcel。您首先编写mString但首先读取mInt。这将有效:

@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);
}

顺便说一句,不要使用原始类型作为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];
        }
    };