【发布时间】:2014-05-05 12:19:35
【问题描述】:
我对@987654321@ 很陌生,并且有点挣扎。我使用 Intent 将实现 Parcelable 的类 Person 的对象传递给另一个活动。
这很好用,但是这个对象已经从Employer 类中实例化了一个对象,当尝试从第二个对象访问方法时,它会抛出一个NullPointerException。我猜是 Parcel 中没有包含 Employer 类对象。
有什么好的做法可以使这项工作发挥作用吗?我的实际代码比这复杂得多,所以我希望我不必重写整个应用程序 :-) 任何想法都非常感谢。
这是我无法开始工作的代码的简化示例:
在 MainActivity.java 中:
Person client = new Person();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable("person",(Person) client);
i.putExtras(b);
i.setClass(this, SecondActivity.class);
startActivity(i);
在 Person.java 中
class Person implements Parcelable{
Company employer;
String lastName;
Person(){
lastName = "Smith";
employer = new Company("Burger King");
}
public String getLastName(){
return lastName;
}
public String getEmployer(){
return employer.getName();
}
}
在 Company.class 中
class Company {
String name;
Company(String companyName){
name = companyName;
}
public String getName(){
return name;
}
}
在 SecondActivity.java 中
Bundle b = this.getIntent().getExtras();
if(b!=null){
Person client = b.getParcelable("person");
String lastName = client.getLastName(); //works fine
String employer = client.getEmployer(); //thows NullPointerException
【问题讨论】:
标签: android android-intent parcelable