Kotlin Parcelable Array Objects Send To Activity

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity.

What is Parcel?

The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.

Create Kotlin Parcelable Array Objects

Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface which needs to be implemented for creating a Parcel for sending the objects from one process to another process.

We will implement or override the following method to implement the Parcelable Objects into the Kotlin.
describeContents() >Describe the kinds of objects contained within this Parcelable instance.
writeToParcel(Parcel dest, int flags) > Create the Parcel of the object.
CREATOR > We also need to create a not-null static method called CREATOR which implements the Parcelable.Creator

Let’s create a class like given below.

class MyData(val FirstName:String,val LastName:String,val Age:Int)  {
}

If you are using the Android Studio it will provide the option to generate and implement the Parcelable to any of the class.

Kotlin Parcelable

 

 

 

It will generate the complete Parcelable code as given below.

package com.nplix.kotlinparcelableexample

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

class MyData(val FirstName:String,val LastName:String,val Age:Int) : Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readInt()) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(FirstName)
        parcel.writeString(LastName)
        parcel.writeInt(Age)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<MyData> {
        override fun createFromParcel(parcel: Parcel): MyData {
            return MyData(parcel)
        }

        override fun newArray(size: Int): Array<MyData?> {
            return arrayOfNulls(size)
        }
    }


}

In above example, we get the code using companion block. This block of code is similar to the static method of the Java. We can access the companion block by referring the name of the class. But for making it a real static method to JVM we need to add the @JvmField annotation.

companion object {
        @JvmField
        val CREATOR = object : Parcelable.Creator<MyData>
        {
            override fun createFromParcel(parcel: Parcel): MyData {
                return MyData(parcel)
            }

            override fun newArray(size: Int): Array<MyData?> {
                return arrayOfNulls(size)
            }
        }
    }

Create Bundle to send the data to second Activity

As a sample, we are adding two item to list using code given below.

//create an array of MyData
        var data:MutableList<MyData> = ArrayList<MyData>()
        var data1:MyData =MyData("Pawan","Kumar",30)
        var data2:MyData =MyData("Rahul","Sharma",32)
        data.add(data1)
        data.add(data2)

Send the above bundle on button click to the second activity.

//send the data to second Activity
        var dataSend:Button=findViewById(R.id.button)
        dataSend.setOnClickListener {
            var intent:Intent=Intent(applicationContext,SecondActivity::class.java)
            intent.putParcelableArrayListExtra("data",data as java.util.ArrayList<out Parcelable>)
            startActivity(intent)
        }

 

Read the Array Object data into the second activity in Kotlin

In second activity we just have to retrieve the intent and get the Parcelable array from this intent.

retrieve the intent using the code as given below.

var intent: Intent =intent

In Java, we use the getIntent() method to get the intent but here we can just use the intent.

var list:List<MyData> = ArrayList<MyData>()
        list=intent.getParcelableArrayListExtra("data")

Using For Loop to iterate all list data in Kotlin

We can use the for loop like given below to display the content of the list, which we get from Main Activity.

for (item in list){
            Log.d("DataMainActivity","Hello "+item.FirstName+" "+item.LastName + " your age is " +item.Age)
        }

Unlike Java where we use the index to retrieve the list item in Kotlin, we can directly refer the item from the list and use it like given above.

If you would like to check the Java version of this tutorial you can check the  Send Array Of Objects To Activity – Android Parcelable

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu