Parcelable Android Pass Data between Activities in Kotlin (Parcelize)

With Parcelable Android, You can pass data as an object between android application components. In the android app if you have one activity that depends on another activity, then you need to pass data between activities. For example, a list of the movie then clicks on the movie go to another activity, where full details about movies will show.

Parcelable Android Pass Data between Activity in Kotlin Parcelize example

In an Android app sending data between activities, you can do with the putExtra and getExtra methods of intent the object. But its works well for basic data types such as string, bool, and Integer not for objects. What will you do if you want to pass an object from one activity to the other? Here you can use the parcelableinterface.

Parcelable interface is great for Android performance but it has too much boilerplate. But in kotlin its easy…lets how?

Parcelize Kotlin

Kotlin added parcelable support in version 1.1.4.

Parcelable support : Android Extensions plugin now includes an automatic Parcelable implementation generator. Declare the serialized properties in a primary constructor and add a @Parcelize annotation, and writeToParcel()/createFromParcel() methods will be created automatically.

Pass data

val intent = Intent(this, SecondActivity::class.java)
    intent.putExtra("student", Student(243, "Rohit Kanojia", 27))
    startActivity(intent)

Receiving Data

val data = intent.extras
val student = data.getParcelable<Student>("student")
val id = student.id.toString()

Let’s start building an Android Parcelable app – Kotlin (Parcelize):

In this example we will just pass a simple data used a Parcelize kotlin in Android.

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. add Android Extensions plugin in dependencies in build.gradle (Module: app)
android {....
    androidExtensions {
        experimental = true
    }
    ....}

And sync the project.

Step 3. Create a Model class “Student.kt” and add the following code
package `in`.eyehunt.parcelableandroidpassdatakotlin

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
/**
 * Created by Eyehunt Team on 19/06/18.
 */
@Parcelize
data class Student (val id:Long, val name: String, val age: Int) : Parcelable  {

}

@Parcelize annotation to your model. That’s it! You don’t need to write any parcel methods anymore! No getter and setter methods. Its a beauty of kotlin Parcelize.

Step 4. Create one more activity “SecondActivity.kt” kotlin class with the layout file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.eyehunt.parcelableandroidpassdatakotlin.SecondActivity">

    <TextView
        android:id="@+id/textView_stu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="36dp"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Show the data in TextView widget.

package `in`.eyehunt.parcelableandroidpassdatakotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_second.*

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        var data = intent.extras
        var student = data.getParcelable<Student>("student")
        textView_stu.text = student.id.toString() + " " + student.name + " " + student.age
    }
}
** Don’t forget to add SecondActivity in AndroidManifest.xml
</manifest>
 </application>
   ...
   <activity android:name="in.eyehunt.parcelableandroidpassdatakotlin.SecondActivity"/>
    </application>
</manifest>
Step 5. add button in main_activity.xml

The button will perform an action to go next Activity.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.eyehunt.parcelableandroidpassdatakotlin.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Hello Eyehunt!"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_send"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Send"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

Set On Click listeners in button button_send.setOnClickListener and Create intent , add following code in MainActivity.kt kotlin class

In intent, you can pass the Parcelable Android Object.

package `in`.eyehunt.parcelableandroidpassdatakotlin

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button_send.setOnClickListener(View.OnClickListener {

            val intent = Intent(this, SecondActivity::class.java)
            intent.putExtra("student", Student(243, "Rohit Kanojia", 27))
            startActivity(intent)
        })
    }
}
Step 7. Run the application, in the emulator or On you android device

Output screenshot Parcelable (Parcelize) Android Pass Data between Activities.

Parcelable Android Pass Data between Activities in Kotlin Parcelize output

Download Parcelable Android Pass Data between Activities in Kotlin – Parcelize source code  :

https://github.com/EyeHunts/ParcelableAndroidPassDataKotlin

 

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Kotlin


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.