Search code examples
androidarraylistparcelable

Parcelable how to use the 'KEY' value when receiving all the information?


I'm making an Android application and I would like to send an ArrayList to the next Activity, but I don't know how to do this with Parcelable.

For example: I got an int named as ID and a String named as Names. I use JSON for getting all informations from PHP and MySQL.

In the for-loop I add all those Names and ID to a class. But then I don't know how to write all these Names and ID into a bundle.putParcelableArrayList(KEY, ArrayList...);, because I don't know how to do this with the KEY value. Do I need to give the KEY value numbers or is there automatically one KEY?

class alleDeelnemers implements Parcelable {

    int id;
    String name;

    /* GETTER AND SETTER */

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(volgnummer);
    }

    public alleDeelnemers(Parcel in) {
        volgnummer = in.readString();
        id = in.readInt();
    }

    // Creator
    public static final Parcelable.Creator CREATOR
            = new Parcelable.Creator() {
        public alleDeelnemers createFromParcel(Parcel in) {
            return new alleDeelnemers(in);
        }

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

Receiving data:

ArrayList<alleDeelnemers> deelnemers = new ArrayList<>();

for(int i=0; i < jArrayDeelnemer.length(); i++)
{
    JSONObject json_data = jArrayDeelnemer.getJSONObject(i);

    //class alleDeelnemers
    deelnemer = new alleDeelnemers();

    //ID
    int ID = json_data.getInt("ID");
    deelnemer.setId(ID);
    //alle deelnemers
    String name = json_data.getString("name ");  
    deelnemer.setName(name );

    //toevoegen in de class
    deelnemers.add(deelnemer);
}

error this line: deelnemer = new alleDeelnemers(); need to build a constructor.


Solution

  • The key is any name you would use to reference your ArrayList. Further in the started activity, you will use this key to retrieve the ArrayList. For example, in the initial activity, do

    bundle.putParcelableArrayList("MY_ARRAY_LIST", deelnemers);
    

    and then in the started activity, to retrieve it later

    Bundle b = getIntent().getExtras();
    ArrayList<alleDeelnemers> list = b.getParcelableArrayList("MY_ARRAY_LIST");
    

    Note that the KEY used here is "MY_ARRAY_LIST". It is a better practice to use xml string constants or an interface for storing constant KEYS.