How to pass data between two activities with jetpack compose?

Last updated Sep 18, 2021

In this Jetpack compose material tutorial we will learn How to pass data between two activities with jetpack compose in Android application. 

Suppose we have two screens Activity A and Activity B. Now when we navigate from A to B i need some data to required at Activity B which is from Activity A. So to pass this data we will use the Intent objects. An activity is basically a single screen in app. We can open a new activity B passing an intent object to startActivity() 

 

Jetpack Ocmpose Activity data pass

Let's get started

Step 1: Create android application in android studio

Step 2: Follow step for setup Jetpack Compose with Android Studio

 

Create 2 ComponentActivity say MainActivity.kt and Activity1.kt

In MainActivity.kt lets add one button on clicking which we are going to launch ActivityA and pass some data through intent.

To send data from activity to another activity we will use intent extras property . It will takes data as key value pair that carries all the additional information for an activity.

 

@Composable
fun ActivityDemo() {
    val context = LocalContext.current
    JetPackTheme() {
        Column(content = {
            Text("Activity 1")
            Text("Name : Rinky")
            Text("Age : 12")
            Text("Gender : Male")
            Text("Param1 : Abhishek")
            Text("Param2 : Shaw")
            Text("Click button below to send data to activity 2")
            Button(onClick = {
                val intent = Intent(context, Activity1::class.java)
                intent.putExtra("Name", "Rinky")
                intent.putExtra("Age", 12)
                intent.putExtra("IsMale", true)
                context.startActivity(intent)
            }) {
                Text("Click")
            }
        }, modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight())
    }
}

 

Intent support only primitive data types to pass data from one screen to other screen. It will support int,String,long,float...

 

Let's pass data as primitive type

 

Here is the simple way to pass the data from one screen to other screen

val intent = Intent(context, Activity1::class.java)

intent.putExtra("Name", "Rinky")

intent.putExtra("Age", 12)

intent.putExtra("IsMale", true)

context.startActivity(intent)

 

in the above code we passed int,Sting,boolean type data

 

How we can pass the object type data between activities?

Intent doesn't provide direct way to pass object type data from one screen to other screen, to pass object type data from one screen to other by two ways

 

  • Convert Object data as String and pass
  • Implement with Parceble object

 

Convert Object to String data type

In this approach we will convert object data to string and pass to the intent. To convert Object to string we are using the GSON converter theory.

 

Add dependency in build.gradle file

api 'com.google.code.gson:gson:2.8.8'

 

 

Let's create a data class

data class JsonData(val param1: String?, val param2: String?)

        object JsonDataOps {
        fun toJson(data: JsonData?): String? {
        try {
            if (data != null) {
                val gsonBuilder = GsonBuilder()
                gsonBuilder.serializeNulls()
                val gson = gsonBuilder.create()
                return gson.toJson(data)
            }

        } catch (e: java.lang.Exception) {

        }
        return null
}

        fun fromStringToData(value: String?): JsonData? {
        try {
            if (value != null) {
                val typeToken = object : TypeToken() {}.type
                val gsonBuilder = GsonBuilder()
                gsonBuilder.serializeNulls()
                val gson = gsonBuilder.create()
                if (gson != null) {
                    val data: JsonData? = gson.fromJson(value, typeToken)
                    return data
                }
            }
        } catch (e: java.lang.Exception) {

        }
        return null
}
    }

 

 

In the above we are converted Object data to string by using gson object

gson.fromJson(value, typeToken)

val intent = Intent(context, Activity1::class.java)
intent.putExtra("Name", "Rinky")
intent.putExtra("Age", 12)
intent.putExtra("IsMale", true)
 val jsonData = JsonData("Abc", "abc@gmail.com")
intent.putExtra("json_data", JsonDataOps.toJson(jsonData))
context.startActivity(intent)

 

Pass Object data between screen by Parcelable format

To pass data as Parcelable we need to implement class with Parcelble interface.

 

Lets create Parcelable class

package com.example.jetpack.datamodels

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

data class ParcelableData(val param1: String?,val param2: String?):Parcelable{
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        parcel.readString()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(param1)
        parcel.writeString(param2)
    }

    override fun describeContents(): Int {
        return 0
    }

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

        override fun newArray(size: Int): Array {
            return arrayOfNulls(size)
        }
    }

}

 

 

Now create an object of  Parcelable Data and send it through putExtra

 

val intent = Intent(context, Activity1::class.java)
intent.putExtra("Name", "Rinky")
intent.putExtra("Age", 12)
intent.putExtra("IsMale", true)
val parcelableData = ParcelableData("Abhishek", "Shaw")
intent.putExtra("parcelable_data", parcelableData)
context.startActivity(intent)

 

 

Full code for MainActivity.kt

package com.example.jetpack

import android.content.Intent
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.example.jetpack.activities.Activity1
import com.example.jetpack.datamodels.*
import com.example.jetpack.ui.theme.JetPackTheme

class MainActivity : ComponentActivity() {

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContent {
        ActivityDemo()
        }
        }
        }


@Composable
fun ActivityDemo() {
        val context = LocalContext.current
        JetPackTheme() {
        Column(
        content = {
        Text("Activity 1")
        Text("Name : Rinky")
        Text("Age : 12")
        Text("Gender : Male")
        Text("Param1 : Abhishek")
        Text("Param2 : Shaw")
        Text("Click button below to send data to activity 2")
        Button(onClick = {
        val intent = Intent(context, Activity1::class.java)
        intent.putExtra("Name", "Rinky")
        intent.putExtra("Age", 12)
        intent.putExtra("IsMale", true)
        val parcelableData = ParcelableData("Abhishek", "Shaw")
        intent.putExtra("parcelable_data", parcelableData)
        val jsonData = JsonData("Abc", "abc@gmail.com")
        intent.putExtra("json_data", JsonDataOps.toJson(jsonData))
        context.startActivity(intent)
        }) {
        Text("Click")
        }
        }, modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
        )
        }
        }


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
        ActivityDemo()
        }

 

 

 

Download Source code

 

 

Full code for Activity1.kt

package com.example.jetpack.activities


import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.example.jetpack.activites.ui.theme.MyApplicationTheme
import com.example.jetpack.datamodels.JsonDataOps
import com.example.jetpack.datamodels.ParcelableData

class Activity1 : ComponentActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
        MyApplicationTheme {
        // A surface container using the 'background' color from the theme
        Surface(color = MaterialTheme.colors.background) {
        ShowData()
        }
        }
        }
        }
        }

@Composable
fun ShowData() {
        val context = LocalContext.current
        val intent = (context as Activity1).intent
        val name = intent.getStringExtra("Name")
        val age = intent.getIntExtra("Age", 0)
        val isMale = intent.getBooleanExtra("IsMale", false)
        val parcelableData = intent.getParcelableExtra("parcelable_data")
        val jsonData = JsonDataOps.fromStringToData(intent.getStringExtra("json_data"))
        Column(
        content = {
        Text("Activity 2")
        Text("Name : $name")
        Text("Age : $age")
        Text("Gender : ${if (isMale) "Male" else "Female"}")
        Text("Parcelable Data")
        Text("Param1 : ${parcelableData?.param1}")
        Text("Param2 : ${parcelableData?.param2}")
        Text("Json Data")
        Text("Param1 : ${jsonData?.param1}")
        Text("Param2 : ${jsonData?.param2}")
        }, modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
        )
        }

@Preview(showBackground = true)
@Composable
fun DefaultPreview2() {
        MyApplicationTheme {
        ShowData()
        }
        }

 

 

Images

Pass data between activities in Android
jetpack compose Pass data between activities in Android

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

5567 Views