Reputation: 36289
I am running into an issue where instantiating an Object
from a Parcel
is throwing a NullPointerException
. My Class Contact implements Parcelable
, contains a CREATOR, and all the hookups seem to work. A Contact object represents a contact in an Address book. The variables used are of types:
String firstName, lastName, note;
List<String> emails, phones;
The constructor initializes all the strings to "" and all the lists to empty lists. The writeToParcel
and Contact(Parcel in)
methods are shown below:
public void writeToParcel(Parcel out, int flags) {
out.writeString(firstName);
out.writeString(lastName);
//If there are emails, write a 1 followed by the list. Otherwise, write a 0
if (!emails.isEmpty())
{
out.writeInt(1);
out.writeStringList(emails);
}
else
out.writeInt(0);
//If there are phone numbers, write a 1 followed by the list. Otherwise, write a 0
if (!phones.isEmpty())
{
out.writeInt(1);
out.writeStringList(phones);
}
else
out.writeInt(0);
out.writeString(note);
}
...
public Contact(Parcel in)
{
firstName = in.readString();
Log.i(TAG, firstName);
lastName = in.readString();
Log.i(TAG, lastName);
int emailsExist = in.readInt();
if (emailsExist == 1)
in.readStringList(emails);
else
emails = new ArrayList<String>();
int phonesExist = in.readInt();
if (phonesExist == 1)
in.readStringList(phones);//Line 80, where this app breaks
else
phones = new ArrayList<String>();
note = in.readString();
}
The test I am currently working on provides a valid first and last name, one phone number, and a note. The relevant output I get when upacking this parcelable is as follows:
FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo...
...
Caused by: java.lang.NullPointerException
at android.os.Parcel.readStringList(Parcel.java:1718)
at com.mycompany.android.Contact.<init>(Contact.java:80) //This is the line marked above
at com.mycompany.android.Contact$1.createFromParcel(Contact.java:40) //This is inside the CREATOR
...
What am I doing incorrectly? Can numbers not be written as String lists, or did I do something incorrectly?
Upvotes: 2
Views: 2163
Reputation: 36289
I just poked around a few minutes more, and realized my mistake. The readStringList
method cannot receive a null argument. My new Contact(Parcel in)
method is as follows:
public Contact(Parcel in)
{
firstName = in.readString();
Log.i(TAG, firstName);
lastName = in.readString();
Log.i(TAG, lastName);
int emailsExist = in.readInt();
emails = new ArrayList<String>();
if (emailsExist == 1)
in.readStringList(emails);
int phonesExist = in.readInt();
phones = new ArrayList<String>();
if (phonesExist == 1)
in.readStringList(phones);
note = in.readString();
}
Upvotes: 2