简体   繁体   English

将包裹类从片段传递到另一个活动

[英]passing parcelable class from fragment to another activity

I usually have no problem with parcelable, but this time i got NPE...and i cant fix it. 我通常对包裹没有问题,但是这次我得到了NPE ...我无法修复它。 Please kindly help me. 请帮助我。

The NPE occurred only when i try to pass the parcelable class from fragment to another activity. 当我尝试将可打包类从片段传递到另一个活动时, 才会发生NPE。 Things working fine if i pass the parcelable class from activity to another activity or from activity to fragment. 如果我将可拆分类从活动传递到另一个活动,或者从活动传递到片段,则一切正常。

This is my fragment code, the child (parcelable class) is NOT null when i debugged it : 这是我的片段代码,当我调试它时, child (可包裹类)不是null:

if(v == imgChild)
{
    Intent i = new Intent(getActivity(), DetailChildActivity.class);
    i.putExtra("child", child);
    startActivity(i);
    Log.d("menu", "children");
}

Here in my target onCreate activity : 在我的目标onCreate活动中:

Bundle data = getIntent().getExtras();
if(data != null)
{
    child = data.getParcelable("child"); //NPE here

    txtName.setText(child.getName());
}

This is strange. 这很奇怪。 The data is NOT null, but the parcelable is always null. 数据不为空,但可拆分项始终为空。

This is my parcelable ( Child ) class : 这是我的包裹类( 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);
}

This is what the log cat said : 这就是log cat所说的:

expected receiver of type com.blabla.child, but got null com.blabla.child类型的预期接收者,但为空

Thanks for your time. 谢谢你的时间。

Strange. 奇怪。 I know the answer, but i dont understand why . 我知道答案, 但是我不明白为什么 Its from FragmentActivity NullPointer in onCreate savedInstanceState Bundle : 它来自onCreate savedInstanceState Bundle中的FragmentActivity NullPointer

public static final Parcelable.Creator

The creator should be in static and final, not just final. 创建者应该处于静态和最终状态,而不仅仅是最终状态。 Thats it. 而已。

Maybe you can explain to me how this work, this is the answer for now. 也许您可以向我解释这是如何工作的,这就是现在的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM