Junior
How to pass data from one activity to another in Android?
sobes.tech AI
Answer from AI
Data can be passed using Intent:
-
In the source Activity: Put data into the
Intent's Extras using methods likeputExtra(String key, value).// Preparing the Intent val intent = Intent(this, TargetActivity::class.java) // Adding data intent.putExtra("myString", "Hello from the first Activity") intent.putExtra("myInt", 123) intent.putExtra("myBool", true) // You can also pass objects that implement Parcelable or Serializable // intent.putExtra("myObject", myParcelableObject) // Starting the new Activity startActivity(intent) -
In the target Activity: Retrieve data from the Extras of the
Intentreceived inonCreateoronNewIntent.// In onCreate() of the target Activity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_target) // Get the Intent that started this Activity val intent = intent // Extract data by key val myString = intent.getStringExtra("myString") val myInt = intent.getIntExtra("myInt", 0) // Second argument is default value val myBool = intent.getBooleanExtra("myBool", false) // Handle the extracted data println("Received string: $myString") println("Received number: $myInt") println("Received boolean: $myBool") // For Parcelable or Serializable objects // val myObject = intent.getParcelableExtra<MyParcelableClass>("myObject") }
Other methods suitable for more complex scenarios or large data volumes include:
ViewModelShared between Fragments/Activities (via SharedViewModel): Convenient for shared data between related components.Bundle(inside Intent Extras):putExtraactually uses aBundleinternally.- Static variables/Singletons: Use cautiously, as they can lead to memory leaks and state issues.
- Database/SharedPreferences: For persistent storage or data transfer requiring saving.
- Event Bus (e.g., EventBus, RxJava): For passing events or data between components asynchronously.
- File I/O: Saving to and reading from a file.