我想将一个对象从一个Details Activity发送到Persons Activity。我按照教程,但收到以下错误:
12-19 08:19:00.434: E/AndroidRuntime(1011): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workingonlist/com.example.workingonlist.Persons}: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.example.workingonlist.Person
这是人物模型:
public class Person implements Parcelable {
private String name;
private String surname;
private String gender;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(Parcel in){
name= in.readString();
surname= in.readString();
gender= in.readString();
}
public Person(String name,String surname,String gender){
this.name=name;
this.surname=surname;
this.gender=gender;
}
// getters and setters
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(gender);
}
private Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Person(source);
}
@Override
public Person[] newArray(int size) {
// TODO Auto-generated method stub
return new Person[size];
}
};
}
这是我要发送Person对象的Details Activity。
private View.OnClickListener onClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btn_save.getId()){
Person p = new Person();
p.setName(et_name.getText().toString());
p.setSurname(et_surname.getText().toString());
switch(rg.getCheckedRadioButtonId()){
case R.id.button1:{
p.setGender("Male");
break;
}
case R.id.button2:{
p.setGender("Female");
break;
}
}
Intent i = new Intent(Details.this,Persons.class);
i.putExtra("person",p);
startActivity(i);
}
}
};
这是我想要获得Person对象的人物活动。
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
PersonAdapter adapter = new PersonAdapter();
setContentView(R.layout.persons);
Bundle b = getIntent().getExtras();
if (b != null) {
Person p = b.getParcelable("person");
adapter.add(p);
}
setListAdapter(adapter);
}
为了解决这个问题,我该怎么办?任何帮助表示赞赏。谢谢。
答案 0 :(得分:4)
您需要设置CREATOR公共静态决赛:
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
答案 1 :(得分:1)
查看处理您的问题的本教程
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
答案 2 :(得分:0)
出于某种原因,我不能对Festus Tamakloe的回答添加评论,但我只是想补充说这对我有帮助。我正在关注一些使用静态创建器的教程。我没有“公开”!
所以请确保你有公开信息。