我遇到了一个问题,即Object
从 a 实例化 aParcel
会抛出NullPointerException
. My Class Contact实现Parcelable
,包含一个 CREATOR,并且所有连接似乎都有效。Contact对象表示通讯簿中的联系人。使用的变量有以下类型:
String firstName, lastName, note;
List<String> emails, phones;
构造函数将所有字符串初始化为 "" 并将所有列表初始化为空列表。和方法writeToParcel
如下Contact(Parcel in)
所示:
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();
}
我目前正在进行的测试提供了有效的名字和姓氏、一个电话号码和一张便条。我在打包这个包裹时得到的相关输出如下:
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
...
我做错了什么?数字不能写成字符串列表,还是我做错了什么?