Pass list of objects in Intent using Kotlin

lawgimenez

Law Gimenez

Posted on May 22, 2021

Pass list of objects in Intent using Kotlin

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();
     }
 }
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

val intent = Intent(this, FinishScanActivity::class.java)
intent.putExtra("list", listItemCount as Serializable)
startActivity(intent)
Enter fullscreen mode Exit fullscreen mode

In your destination Activity, you retrieved the list.

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

And that’s it.

💖 💪 🙅 🚩
lawgimenez
Law Gimenez

Posted on May 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related