Pass list of objects in Intent using Kotlin

Posted on May 21, 2021

Every Android developer is familiar with passing data between Activities using Bundle. The old Java way was to implement Parcelable class and then you override all the required methods. See example below. You can read more of the details here.

public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

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

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

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

I'm not really a fan of this type of implementation because it will make my data class more difficult to read and confusing.

Typically it is complicated to pass a list of objects between Activities. But lately in Kotlin all you have to do is simple.

First, in your data class you implement Serializable.

@Entity
data class ItemCount(
    @ColumnInfo(name = "id") val itemID: Int,
    @ColumnInfo(name = "name") val name: String
): Serializable {
    @PrimaryKey(autoGenerate = true) var id: Int? = null
}

Then in your source Activity, you add it to your bundle and cast it as Serializable.

val intent = Intent(this, DestinationActivity::class.java)
intent.putExtra("list", listItemCount as Serializable)
startActivity(intent)

In your destination Activity, you retrieved the list.

val listItemCount: MutableList<ItemCount>  = intent.getSerializableExtra("list") as MutableList<ItemCount>

And that's it.