【发布时间】:2014-10-08 07:53:23
【问题描述】:
我通常对 parcelable 没有任何问题,但这次我得到了 NPE……我无法修复它。请帮助我。
NPE 仅在我尝试将 parcelable 类从片段传递到另一个活动时发生。如果我将 parcelable 类从活动传递到另一个活动或从活动传递到片段,那么一切正常。
这是我的片段代码,child(parcelable 类)在我调试时不为空:
if(v == imgChild)
{
Intent i = new Intent(getActivity(), DetailChildActivity.class);
i.putExtra("child", child);
startActivity(i);
Log.d("menu", "children");
}
在我的目标onCreate 活动中:
Bundle data = getIntent().getExtras();
if(data != null)
{
child = data.getParcelable("child"); //NPE here
txtName.setText(child.getName());
}
这很奇怪。数据不为空,但 parcelable 始终为空。
这是我的 parcelable (Child) 类:
public final Parcelable.Creator<Child> CREATOR = new Parcelable.Creator<Child>() {
public Child createFromParcel(Parcel in) {
return new Child(in);
}
public Child[] newArray(int size) {
return new Child[size];
}
};
private Child(Parcel in) {
id = in.readInt();
user_id = in.readInt();
name = in.readString();
gender = in.readString();
born_date = in.readString();
born_hour = in.readString();
hospital = in.readString();
result = in.readString();
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeInt(id);
dest.writeInt(user_id);
dest.writeString(name);
dest.writeString(gender);
dest.writeString(born_date);
dest.writeString(born_hour);
dest.writeString(hospital);
dest.writeString(result);
}
log cat 是这么说的:
预期为 com.blabla.child 类型的接收器,但为空
感谢您的宝贵时间。
【问题讨论】:
-
您能否将完整的跟踪以及将对象读取和写入包裹的代码发布回来?谢谢
-
@Fred 抱歉,您所说的“完整跟踪”是什么意思?我将发布我的读写可打包代码,谢谢
-
所以等一下,
Bundle data = getIntent().getExtras();是空的吗? -
@Zhuinden 不,数据不是空的。但是子对象可以。
-
各位 非常感谢,我已经解决了这个问题。我会尽快回答我自己的问题
标签: android android-intent parcelable