Android
Activities
Data Passing
Intents
Mobile Development

How do I pass data between Activities in Android application?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When developing Android applications, efficiently passing data between activities is a fundamental skill. Multiple approaches are available, each with its own use cases and technical considerations. This document will explore these methods, explain their implementations with code examples, and conclude with a comparison table summarizing these techniques.

Intent Extras

Intent is a staple mechanism for passing data between activities in Android. You create an Intent object and attach data using key-value pairs stored as extras. This is suitable for simple data types such as primitives (int, float, double), strings, and other serializable objects.

Example:

kotlin
1// Starting Activity A
2val intent = Intent(this, ActivityB::class.java)
3intent.putExtra("KEY_NAME", "John")
4intent.putExtra("KEY_AGE", 25)
5startActivity(intent)
6
7// Receiving Activity B
8override fun onCreate(savedInstanceState: Bundle?) {
9    super.onCreate(savedInstanceState)
10    setContentView(R.layout.activity_b)
11
12    val name = intent.getStringExtra("KEY_NAME")
13    val age = intent.getIntExtra("KEY_AGE", 0)
14    // Use the data
15}

Key Considerations:

  • Best for small amounts of data.
  • Simple and efficient for primitive data types and strings.
  • Intent extras must implement the Serializable or Parcelable interface for complex objects.

Bundles

Bundles are essentially collections of key-value pairs, similar to Intent extras, but with the added advantage of nested data structures. You can pass a Bundle object through an Intent.

Example:

kotlin
1// Starting Activity A
2val bundle = Bundle()
3bundle.putString("KEY_NAME", "John")
4bundle.putInt("KEY_AGE", 25)
5
6val intent = Intent(this, ActivityB::class.java)
7intent.putExtras(bundle)
8startActivity(intent)
9
10// Receiving Activity B
11override fun onCreate(savedInstanceState: Bundle?) {
12    super.onCreate(savedInstanceState)
13    setContentView(R.layout.activity_b)
14
15    val bundle = intent.extras
16    val name = bundle?.getString("KEY_NAME")
17    val age = bundle?.getInt("KEY_AGE")
18    // Use the data
19}

Key Considerations:

  • Useful when passing complex data.
  • Acts like a lightweight map for organizing properties.

Parcelable

Parcelable is a more efficient alternative to Serializable for complex data due to its ability to serialize data directly into a Parcel. This makes it ideal for passing custom objects between activities.

Example:

kotlin
1// User.kt
2import android.os.Parcelable
3import kotlinx.android.parcel.Parcelize
4
5@Parcelize
6data class User(val name: String, val age: Int): Parcelable
7
8// Starting Activity A
9val user = User("John", 25)
10val intent = Intent(this, ActivityB::class.java)
11intent.putExtra("USER_KEY", user)
12startActivity(intent)
13
14// Receiving Activity B
15override fun onCreate(savedInstanceState: Bundle?) {
16    super.onCreate(savedInstanceState)
17    setContentView(R.layout.activity_b)
18
19    val user = intent.getParcelableExtra<User>("USER_KEY")
20    // Use the user object
21}

Key Considerations:

  • Requires more boilerplate than Serializable.
  • Must implement the Parcelable interface.
  • Better performance than Serializable.

Serializable

While not recommended for performance-critical applications, Serializable is a straightforward way to pass objects of classes that implement Serializable. Unlike Parcelable, it uses reflection and is thus slower.

Example:

java
1import java.io.Serializable;
2
3public class User implements Serializable {
4    private String name;
5    private int age;
6
7    public User(String name, int age) {
8        this.name = name;
9        this.age = age;
10    }
11
12    // getters and setters
13}
14
15// Starting Activity A
16User user = new User("John", 25);
17Intent intent = new Intent(this, ActivityB.class);
18intent.putExtra("USER_KEY", user);
19startActivity(intent);
20
21// Receiving Activity B
22User user = (User) getIntent().getSerializableExtra("USER_KEY");
23// Use the user object

Key Considerations:

  • Simpler as it leverages Java's built-in serialization.
  • Can lead to slower performance due to reflection.

Shared Preferences

Not typically intended for data passing between activities, SharedPreferences can be used for persistent storage. Data is stored in key-value pairs and remains accessible across multiple app sessions, making it suitable for small amounts of primitive or string data.

Example:

kotlin
1// Writing data in Activity A
2val sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
3with (sharedPref.edit()) {
4    putString("KEY_NAME", "John")
5    putInt("KEY_AGE", 25)
6    apply()
7}
8
9// Retrieving data in Activity B
10val sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
11val name = sharedPref.getString("KEY_NAME", null)
12val age = sharedPref.getInt("KEY_AGE", 0)
13// Use the data

Key Considerations:

  • Best for simple and persistent data storage.
  • Not ideal for high-frequency data transfer between activities.

Comparison Table

Here is a comparison of the different data-passing techniques in terms of use-case, complexity, and other factors.

MethodUse CaseComplexityComplete LifecycleData Type SuitabilityEfficiency
Intent ExtrasSmall, simple data typesSimpleShort/ActivityPrimitives, StringsHigh
BundlesNested data typesModerateShort/ActivityComplex structuresHigh
ParcelableCustom class objectsHighShort/ActivityCustom objectsVery High
SerializableCustom class objectsLowShort/ActivityCustom objectsLow
SharedPreferencesPersistent small dataSimplePersistent/GlobalPrimitives, StringsModerate

In conclusion, the choice of method for passing data between activities largely depends on the nature of the data, efficiency, and the intended lifecycle of the data. Understanding the strengths and weaknesses of each approach ensures optimal app performance and a cleaner codebase.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.