0
0
Android Kotlinmobile~5 mins

Passing data between activities in Android Kotlin

Choose your learning style9 modes available
Introduction

Sometimes you want to send information from one screen to another in your app. Passing data between activities lets you do that easily.

You want to send a username from a login screen to a welcome screen.
You need to pass a selected item from a list screen to a detail screen.
You want to share user input from one form to another screen for confirmation.
Syntax
Android Kotlin
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", value)
startActivity(intent)
Use putExtra() to add data to the Intent before starting the new activity.
In the receiving activity, use intent.getExtra("key") to get the data.
Examples
Sends an integer with key "itemId" to DetailActivity.
Android Kotlin
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra("itemId", 123)
startActivity(intent)
Sends a string with key "username" to ProfileActivity.
Android Kotlin
val intent = Intent(this, ProfileActivity::class.java)
intent.putExtra("username", "Alice")
startActivity(intent)
Sample App

This example has two activities. MainActivity sends a string message to SecondActivity when a button is clicked. SecondActivity shows the message on screen.

Android Kotlin
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val button = findViewById<Button>(R.id.buttonSend)
    button.setOnClickListener {
      val intent = Intent(this, SecondActivity::class.java)
      intent.putExtra("message", "Hello from MainActivity")
      startActivity(intent)
    }
  }
}

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

    val message = intent.getStringExtra("message")
    val textView = findViewById<TextView>(R.id.textViewMessage)
    textView.text = message ?: "No message received"
  }
}
OutputSuccess
Important Notes

Always use the same key string to send and receive data.

Data types must match when you putExtra and getExtra (e.g., String, Int).

Use null checks or default values when getting data to avoid crashes.

Summary

Use Intent and putExtra() to send data between activities.

Retrieve data in the new activity with get<Type>Extra() using the same key.

Passing data helps screens share information smoothly in your app.