Sending Nested Parcelable with Intent

前端 未结 3 1191
粉色の甜心
粉色の甜心 2021-01-21 10:31

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

相关标签:
3条回答
  • 2021-01-21 11:11

    You are not assigning data to var variable in constructor.

    change it like

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

    Edit::

    Change your code like this and try

    @Override
    public void writeToParcel(Parcel dest, int flags) {
    
        B[] data = new B[var.size()];
        for (int i = 0; i < data.length; i++) {
            data[i] = var.get(i);
        }
        dest.writeParcelableArray(data, flags);
    
    }
    
    public A(Parcel in) {
        Parcelable[] parcelables = in.readParcelableArray(Thread
                .currentThread().getContextClassLoader());
        ArrayList<B> list = new ArrayList<B>();
        for (Parcelable parcelable : parcelables) {
            list.add((B) parcelable);
        }
        var = list;
    }
    
    0 讨论(0)
  • 2021-01-21 11:36

    You have to instanciate your ArrayList< B > in :

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

    Say if it works :)

    0 讨论(0)
  • 2021-01-21 11:38

    you have problem with parsing the arraylist... do these changes..

    private A (Parcel in){
            in.readTypedList(this.var, B.CREATOR);
    }
    

    to

    this.var=in.readArrayList(B.class.getClassLoader());
    

    and

    public void writeToParcel(Parcel dest, int flags) {
            dest.writeTypedList(this.var);
    }
    

    to

    dest.writeList(this.var);
    
    0 讨论(0)
提交回复
热议问题