Search code examples
javaandroidandroid-intentarraylistparcel

NotSerializable exception with intent.addExtra(parcelable Object)


I'm attempting to transfer one object containing an ArrayList of other Objects to another Activity in Android. The idea is to add those to an ArrayList and display them so that the Task in question can be performed.

Task ta = new Task(n, o, t, v, subList);

    Intent i = new Intent(this, ActivityList.class);
    i.putExtra("task", ta);
    startActivity(i);

This is the intent. Task is Parcelable, and the subList is an ArrayList of class Subtask which is also Parcelable. Surely, since ArrayList always implement Serializable, Parcelling them shouldn't be a problem? The constructor arguments are: String, byte, byte, byte, ArrayList. The bytes are to be used as booleans.

Here is the Parcel code for Task if you need it:

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(taskName);
    dest.writeByte((byte) (soundCueOne ? 1 : 0));
    dest.writeByte((byte) (soundCueTwo ? 1 : 0));
    dest.writeByte((byte) (vibrCue ? 1 : 0));
    dest.writeSerializable(myList);
}

private Task(Parcel in) {
    this.taskName = in.readString();
    this.soundCueOne = in.readByte() != 0;
    this.soundCueTwo = in.readByte() != 0;
    this.vibrCue = in.readByte() != 0;
    this.myList = (ArrayList<Subtask>) in.readSerializable();
}

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

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

Can anyone see what is wrong with the code? It's obviously somewhere, maybe even in the Subtask class, since the emulator crashes as soon as the Task is constructed and it tries to Parcel it.


Solution

  • If I see correctly, then the problem is that you are trying to use the ArrayList<T> as a Serializable, even though it is not a Serializable - it is a Parcelable.

    Therefore, replace

    dest.writeSerializable(myList);
    

    with

    dest.writeTypedList(myList);
    

    and replace

    this.myList = (ArrayList<Subtask>) in.readSerializable();
    

    with

    this.myList = in.readTypedList(new ArrayList<Subtask>(), Subtask.CREATOR);