0
0
Android Kotlinmobile~5 mins

Passing arguments in Android Kotlin

Choose your learning style9 modes available
Introduction

Passing arguments lets you send information from one screen to another in your app. This helps screens show different content based on what you send.

When you want to open a details screen showing info about a selected item.
When you need to send user input from one screen to another for processing.
When navigating between screens that share data like user ID or settings.
When you want to customize the next screen based on choices made earlier.
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 screen.
The key is a String to identify the data; value can be a String, Int, Boolean, etc.
Examples
Sends an integer 42 with key "itemId" to DetailActivity.
Android Kotlin
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra("itemId", 42)
startActivity(intent)
Sends a String "Alice" with key "username" to ProfileActivity.
Android Kotlin
val intent = Intent(this, ProfileActivity::class.java)
intent.putExtra("username", "Alice")
startActivity(intent)
Sends a Boolean true with key "notificationsEnabled" to SettingsActivity.
Android Kotlin
val intent = Intent(this, SettingsActivity::class.java)
intent.putExtra("notificationsEnabled", true)
startActivity(intent)
Sample App

This app has two screens. When you tap the button on the first screen, it opens the second screen and sends a message. The second screen shows the message in a text view.

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

    val button = findViewById<Button>(R.id.button)
    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.textView)
    textView.text = message ?: "No message received"
  }
}
OutputSuccess
Important Notes

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

Check for null when getting extras to avoid crashes if data is missing.

You can pass many types of data, but complex objects need special handling.

Summary

Passing arguments lets screens share information easily.

Use Intent and putExtra() to send data when starting a new screen.

Retrieve data in the new screen using getIntent().getXExtra() methods.