Looking For Anything Specific?

Android Kotlin Tutorial On How to Pass Data Between Activities

In this tutorial we are going to learn how to pass data from one activity to another activity in android with kotlin by using Intents,  You can learn more about activities in this below android developers page 

The Activity class is a crucial component of an Android app, and the way activities are launched and put together is a fundamental part of the platform's application model.

As described above activities are the fundamental part of an application, an android application has more than one activity, also some simple applications are having only one activity whereas they use fragments with them. In case if you're building an application and want to send data from one activity to another this tutorial will help you learn that we have also included our complete kotlin code below which you can download from Github. 

How To Create RecyclerView With Multiple View Types In Kotlin

Andoird ViewPager2 Tutorial In Kotlin With Sample Code

Pass Data Between Activities Using Intent:

Earlier In our blog, we have shared this article about android intents and what you can do with it, Android Intent With Kotlin Sample Code, You can learn some of the basics of android intent there, where we start another activity from MainActivity using Intent, like the same we are also going to do here, with that we will be passing data in the Intent to our SecondActivity  You can get more information about android intent here: Intent and Intent filters - Android Developers

For this tutorial, you need to create two activities one is MainActivity and the second is SecondActivity - for easy understanding. In the MainActivity add an edit text and button those will be used to send data to the second activity like below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:hint="Enter Text to Send to Second Activity"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:text="Send Data"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

So for this layout, we have an edit text and a button where we get the text from the edit text and send it to the second activity when we press the button. You can learn how to set on click listener to a button in kotlin here  [Tutorial] How to setOnClickListener in Android Button Click with  Kotlin, now open your MainActivity.kt file, We need to add a click listener to the button also need to check that the text is not empty, after doing so we can send the data in our case it would be string, to the next activity, When passing data between activities we are not limited to the string we can pass any data types to another activity via Intent, Below is the code to send data to another activity in kotlin 

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val button = findViewById<Button>(R.id.button)
        val editText = findViewById<EditText>(R.id.editText)

        button.setOnClickListener{
            if (editText.text.toString().isNotEmpty() ){
                val intent = Intent(this,SecondActivity::class.java)
                intent.putExtra("message",editText.text.toString())
                startActivity(intent)
            }else{
                Toast.makeText(this,
                    "Text is empty, please enter something",
                    Toast.LENGTH_SHORT).show()
            }

        }
    }
}

In the above code, we have added a click listener to our button, so when the button is clicked we execute the code within it, what we did there is that we first checked the text whether it is empty or not, if it is empty we show a little toast message to make it more realistic, You can learn about Toast message with kotlin here : [Tutorial] How to Show Toast Message  In Android From Activity with Kotlin, After knowing that our text is not empty we can use Android intent to pass data between activity, For that we have to create a new intent object with context and the destination activity, then call the method putExtra in the intent object which accepts a large number of argument types followed as a key value pair, the first parameter of the function is the key which is a string and the second value of the parameter could be anything from Integer, Float even Arrays can be passed with intent putExtra function, for our case we have sent the text from our edit text to the intents, and finally start the activity by calling startActivity by passing the intent object we created.

android pass data between activites


Receive Data From Intent:

Once we have passed the data successfully, now we can access the value in the receiver activity which is the second activity, for to make it more realistic I have added a text view to show our data passed through intent, below is the layout file for the second activity

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".SecondActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

This is a simple textview inside a constraint layout, Although you can do much more to your textview, learn more about that here on :[Tutorial] How to Customize Android TextView in XML. Now we can look into our activity class to receive the data we passed through intent 

SecondActivity.kt

class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        val extras = intent.extras
        val fromExtras = extras?.getString("message")
        fromExtras?.let {
            findViewById<TextView>(R.id.textView).text = it
        }
    }
}

In our second activity, we can get the value from the activities intent, get a reference to the extras in the intent, and from that extras get the value by calling the appropriate method and passing the correct key value for example if you passed a string called the function getString(key: String) method in the extras, it will return the value if it has or null if there is no value associated with that key so we have to do a null check before accessing the value.

android receive data from intent


Also, you can use hasExtras function directly onto an intent to avoid null values like below


if(intent.hasExtra("message")){
     val message =intent.getStringExtra("message")
     findViewById<TextView>(R.id.textView).text = message
}
With this approach, we are checking whether the message is in the extras or not, the hasExtras function will return a boolean if that extra has a value associated with that key.

Learn Here on How To Use Custom Contract With Activity Result API With Kotlin

This tutorial only covers one part of the implementation where as you can only send data to another activity while starting, what if you wanted to get a result from the started activity well for that you can use startActivityForResult but it is deprecated so here we published an article about the new ActivityResult API in android with sample code check it out

 [Tutorial] Get Android Activity Result in Kotlin With ActivityResult API

Learn How to Store Data In Android With Shared Preference In Kotlin


The reference of the intent in the second activity is a get function that returns an intent that started the activity. Below is the sample output of the above code




Here we conclude this article with this information, there are some other  tutorials you might be interested in :

!!!Spread The Word!!!