Intent putExtra with array of object implementing Parcelable

1.8k views Asked by At

I want to add an array of instances of Person class, this class implements Parcelable. I tried the code below

setResult(Activity.RESULT_OK, new Intent().putExtra("persons", persons));
finish();

to store the array in an intent from the sender activity, and the next code in the reciever activity to retrieve it

if(requestCode == PERSON_REQUEST_CODE && resultcode == Activity.RESULT_OK)
    persons = (Person[]) data.getParcelableArrayExtra("persons"); // persons is Person[]

however, I'm getting an error when running it

07-26 06:29:59.560: E/AndroidRuntime(632): Caused by: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called  CREATOR on class Person

Is it not running because I'm casting the array to Person[]?

EDIT

Here is my Person class

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
    private String fname;
    private String lname;

    public Person() {}

    Person(Parcel in) {
        this.fname = in.readString();
        this.lname = in.readString();
    }

    public void setFirstName(String fname) { this.fname = fname; }
    public void setLastName(String lname)  { this.lname = lname; }

    public String getFirstName() { return fname; }
    public String getLastName()  { return lname; }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(fname);
        dest.writeString(lname);
    }

    static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }

        @Override
        public Person createFromParcel(Parcel source) {
            return new Person(source);
        }
    };
}

EDIT #2

I was able to solve it by writing the following code

Parcelable[] parcelablePersons = data.getParcelableArrayExtra("persons");
persons = new Person[parcelablePersons.length];
for(int i = 0; i < parcelablePersons.length; i++) {
    persons[i] = (Person) parcelablePersons[i];
}
1

There are 1 answers

0
Kevin Coppock On

Your CREATOR instance must be public. Currently it's package private.