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();
     }
 }

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close