Search code examples
androidarraylistparcelable

ArrayList and Parcelable


I need to "transfer" an ArrayList of custom class from one entity to another. I know that I need to implement Parcelable interface.

This is my custom class.

public class cSportsList implements Parcelable {
    boolean checked;
    String name;

    cSportsList(boolean check, String name_) {
        checked = check;
        name = name_;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //Non posso passare un booleano e non posso fare il cast boolean -> int
        if (checked) {
            dest.writeInt(1);
        }
        else dest.writeInt(0);
        dest.writeString(name);
    }

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

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

    private cSportsList(Parcel in) {
        if (in.readInt() == 1) {
            checked = true;
        }
        else {
            checked = false;
        }
        name = in.readString();


    }
}

And this is the code in entity "from"

//This is sportsMap: ArrayList<cSportsList> sportsMap = new ArrayList<cSportsList>();
Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class);
intent.putParcelableArrayListExtra("sportsMap", (ArrayList<? extends Parcelable>)  sportsMap);  //I have tried with ArrayList<cSportsList> too.
this.startActivity(intent);

And this is the code in entity "to"

final Intent srcIntent = getIntent();
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap");

The problem is: in entity "To" sportsMap is null. If I set "breakpoint" in "writeToParcel" and "cSportsList(Parcelable in)" functions I see that the code is executed for both functions.

Where is my error ?

Thanks. M.


Solution

  • Use the below code

    sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");