I am quite new to Parcelables
and are struggling a bit. I pass an object of class Person
which implements Parcelable
to another activity using Intent.
That works fine, but this object has instantiated an object from the Employer
class, and when trying to access methods from this second object it thows a NullPointerException
. I guess it is the Employer class object that is not included in the Parcel.
Any ideas for a good practice to make this work? My actual code is a lot more complicated than this, so I hope I don't have to rewrite the enitre app :-) Any ideas is highly appreciated.
Here is a simplified sample of the code I can not get to work:
In 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);
In 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();
}
}
In Company.class
class Company {
String name;
Company(String companyName){
name = companyName;
}
public String getName(){
return name;
}
}
In 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