我想添加一个类的实例数组Person
,这个类实现了Parcelable
. 我尝试了下面的代码
setResult(Activity.RESULT_OK, new Intent().putExtra("persons", persons));
finish();
将数组存储在发送者活动的意图中,并在接收者活动中的下一个代码来检索它
if(requestCode == PERSON_REQUEST_CODE && resultcode == Activity.RESULT_OK)
persons = (Person[]) data.getParcelableArrayExtra("persons"); // persons is Person[]
但是,运行它时出现错误
07-26 06:29:59.560: E/AndroidRuntime(632): Caused by: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class Person
它没有运行是因为我将数组投射到Person[]
吗?
编辑
这是我的Person
课
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String fname;
private String lname;
public Person() {}
Person(Parcel in) {
this.fname = in.readString();
this.lname = in.readString();
}
public void setFirstName(String fname) { this.fname = fname; }
public void setLastName(String lname) { this.lname = lname; }
public String getFirstName() { return fname; }
public String getLastName() { return lname; }
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fname);
dest.writeString(lname);
}
static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person[] newArray(int size) {
return new Person[size];
}
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
}
};
}
编辑#2
我能够通过编写以下代码来解决它
Parcelable[] parcelablePersons = data.getParcelableArrayExtra("persons");
persons = new Person[parcelablePersons.length];
for(int i = 0; i < parcelablePersons.length; i++) {
persons[i] = (Person) parcelablePersons[i];
}