How to pass data between activities in Kotlin Android
How to pass data between activities in Kotlin Android.
Here is a detailed step-by-step tutorial on how to pass data between activities in Kotlin Android:
Step 1: Create a new Android project
First, create a new Android project in Android Studio. Choose an appropriate project name and set the minimum SDK version.
Step 2: Create two activities
In this tutorial, we will create two activities: MainActivity and SecondActivity. MainActivity is the starting activity and SecondActivity is the activity to which we will pass data.
To create a new activity, right-click on the package name in the project explorer, go to New -> Activity -> Empty Activity. Repeat this process to create the SecondActivity.
Step 3: Define UI elements
Open the layout XML files for MainActivity and SecondActivity. Add any desired UI elements such as TextViews, EditTexts, or Buttons to each layout file.
Step 4: Define data passing mechanism
There are several ways to pass data between activities in Android. In this tutorial, we will cover two common methods: using Intent extras and using Parcelable.
Method 1: Using Intent extras
To pass data using Intent extras, follow these steps:
In MainActivity, create an Intent object to start the SecondActivity:
val intent = Intent(this, SecondActivity::class.java)
Add data to the Intent using
putExtra()
method. For example, if you want to pass a string value:intent.putExtra("key", "Hello from MainActivity")
Start the SecondActivity using
startActivity()
method:startActivity(intent)
In SecondActivity, retrieve the data from the Intent in the
onCreate()
method:val data = intent.getStringExtra("key")
Method 2: Using Parcelable
To pass custom objects between activities using Parcelable, follow these steps:
Create a data class that implements the Parcelable interface. For example, create a class named "Person":
data class Person(val name: String, val age: Int) : Parcelable {
// Implement Parcelable methods here
}Implement the required methods for the Parcelable interface. Android Studio will prompt you to generate the methods automatically. If not, you can manually implement them.
In MainActivity, create an instance of the custom object:
val person = Person("John Doe", 25)
Create an Intent and add the custom object as an extra:
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("person", person)Start the SecondActivity:
startActivity(intent)
In SecondActivity, retrieve the custom object from the Intent in the
onCreate()
method:val person = intent.getParcelableExtra<Person>("person")
Step 5: Display the passed data
To display the passed data in SecondActivity, update the UI elements with the received data. For example, if you have a TextView with the id "textViewName", you can set its text as follows:
textViewName.text = person.name
That's it! You have successfully passed data between activities in Kotlin Android using Intent extras and Parcelable.