有意发送嵌套包裹 [英] Sending Nested Parcelable with Intent

查看:63
本文介绍了有意发送嵌套包裹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送一个Parcelable对象,其中也包含另一个具有Intent的Parcelable对象.但是,我收到NullPointer异常.你能告诉我我在哪里做错了吗?

I am trying to send a Parcelable object which also contains another Parcelable object with Intent. However, I am getting NullPointer Exception. Could you please tell me where I am doing wrong?

A.java

public class A  implements Parcelable {

    private ArrayList<B> var;

    public A()
    {
        this.var = new ArrayList<B>();  
    }

    public void addToB(B b)
    {
        var.add(b);
    }


    public ArrayList<B> getB() {
        return var;
    }

    public void setB(ArrayList<B> b) {
        this.var = b;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeTypedList(this.var);

    }

    private A (Parcel in){

        in.readTypedList(this.var, B.CREATOR);
    }

    public static final Parcelable.Creator<A> CREATOR = new Parcelable.Creator<A>() {
        public A createFromParcel(Parcel in) {
            return new A(in);
        }

        public A[] newArray(int size) {
            return new A[size];
        }
    };

}

B.java

public class B implements Parcelable  {

    private String type;


    public B(String type)
    {
        this.type=type;
    }

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel arg0, int arg1) {
        arg0.writeString(this.type);        
    }

    private B(Parcel in) {
        this.type=in.readString();
    }

    public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };

}

我这样发送带有Intent的A对象:

I send the A object with Intent like this:

Intent i = new Intent(Bla.this, Blabla.class);
            i.putExtra("info", objectA);
            startActivity(i);

我收到这样的包裹:

Intent i = getIntent();
        ObjectA ci = (ObjectA)i.getParcelableExtra("info");

推荐答案

您必须实例化ArrayList<B>在:

You have to instanciate your ArrayList< B > in :

 private A (Parcel in){
    var = new ArrayList<B>();
    in.readTypedList(this.var, B.CREATOR);
}

说是否可行:)

这篇关于有意发送嵌套包裹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆