0
0
Android Kotlinmobile~15 mins

Passing data between activities in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Passing data between activities
What is it?
Passing data between activities means sending information from one screen to another in an Android app. Activities are like pages or screens, and sometimes you need to share data like text, numbers, or objects when moving from one screen to the next. This process helps keep the app interactive and personalized for the user.
Why it matters
Without passing data between activities, each screen would be isolated and unable to share user choices or information. This would make apps less useful and frustrating because users would have to re-enter data or lose progress. Passing data keeps the app connected and responsive to user actions.
Where it fits
Before learning this, you should understand what activities are and how to navigate between them. After this, you can learn about saving data permanently or sharing data between fragments and other components.
Mental Model
Core Idea
Passing data between activities is like handing a note from one person to another when moving between rooms, so the next person knows what you want to share.
Think of it like...
Imagine you are at a party moving from the living room to the kitchen. You want to tell your friend in the kitchen what music to play, so you write it on a sticky note and hand it to them as you enter. The sticky note is the data you pass between activities.
Activity A (Sender) ──> [Intent with Extras] ──> Activity B (Receiver)

┌─────────────┐       ┌─────────────┐
│ Activity A  │       │ Activity B  │
│ (Screen 1)  │       │ (Screen 2)  │
└─────────────┘       └─────────────┘
       │                     ▲
       │  Intent with data    │
       └─────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Activities and Intents
🤔
Concept: Learn what activities and intents are in Android and how they relate to screens and navigation.
An activity is a single screen in an Android app. To move from one activity to another, Android uses an Intent, which is like a message saying "go to this screen." Intents can carry extra information called extras.
Result
You understand that activities are screens and intents are messages that can carry data between them.
Knowing that intents are the vehicle for navigation and data transfer helps you see how Android apps move and share information.
2
FoundationCreating and Starting an Intent
🤔
Concept: Learn how to create an intent to start another activity.
In Kotlin, you create an Intent object specifying the current activity and the target activity. Then you call startActivity(intent) to open the new screen. Example: val intent = Intent(this, SecondActivity::class.java) startActivity(intent)
Result
The app moves from the current screen to the second screen when the intent is started.
Understanding how to start activities is the first step before adding data passing.
3
IntermediateAdding Simple Data to Intents
🤔Before reading on: do you think you can send complex objects directly through intents or only simple data types? Commit to your answer.
Concept: Learn how to add simple data like strings or numbers to an intent using extras.
You can attach data to an intent using putExtra(key, value). For example, to send a string: val intent = Intent(this, SecondActivity::class.java) intent.putExtra("username", "Alice") startActivity(intent) In the receiving activity, you get the data with: val username = intent.getStringExtra("username")
Result
The second activity receives the string "Alice" and can use it to personalize the screen.
Knowing how to attach and retrieve simple data types lets you customize screens based on user input or app state.
4
IntermediatePassing Multiple Data Items
🤔Before reading on: do you think you need a separate intent for each piece of data or can you send many at once? Commit to your answer.
Concept: Learn how to send multiple pieces of data in one intent using multiple extras.
You can add many extras to the same intent: intent.putExtra("username", "Alice") intent.putExtra("age", 25) intent.putExtra("isMember", true) In the receiving activity, retrieve each: val username = intent.getStringExtra("username") val age = intent.getIntExtra("age", 0) val isMember = intent.getBooleanExtra("isMember", false)
Result
The receiving activity gets all the data and can use it to adjust the UI or logic.
Understanding that one intent can carry many data items simplifies passing complex information.
5
IntermediatePassing Complex Data with Parcelable
🤔Before reading on: do you think you can send custom objects directly through intents without extra work? Commit to your answer.
Concept: Learn how to pass custom objects by making them Parcelable, a special interface for Android data transfer.
Simple data types work out of the box, but custom objects need to implement Parcelable. Example: @Parcelize class User(val name: String, val age: Int) : Parcelable Send: intent.putExtra("user", userObject) Receive: val user = intent.getParcelableExtra("user") This requires adding the kotlin-parcelize plugin and @Parcelize annotation.
Result
You can send whole objects between activities, keeping data organized and reusable.
Knowing Parcelable unlocks powerful data sharing beyond simple types, essential for real apps.
6
AdvancedHandling Null and Default Values Safely
🤔Before reading on: do you think getStringExtra always returns a non-null value? Commit to your answer.
Concept: Learn to safely handle missing or null data when retrieving extras to avoid crashes.
Extras might be missing or null. Use safe calls and default values: val username = intent.getStringExtra("username") ?: "Guest" val age = intent.getIntExtra("age", -1) Check for null before using data to prevent app crashes.
Result
Your app handles missing data gracefully and stays stable.
Understanding null safety prevents common runtime errors and improves user experience.
7
ExpertUsing Intent Flags and Data Passing Pitfalls
🤔Before reading on: do you think intent flags affect data passing or just navigation? Commit to your answer.
Concept: Learn how intent flags affect activity behavior and how they can impact data passing unexpectedly.
Intent flags like FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP change how activities are launched or reused. If an activity is reused, onNewIntent() is called instead of onCreate(), so data must be handled there. Example: override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent?.let { val data = it.getStringExtra("key") // handle data } } Ignoring this can cause data to be missed or stale.
Result
You correctly handle data even when activities are reused, avoiding bugs.
Knowing how intent flags affect lifecycle and data flow helps build robust navigation and data passing.
Under the Hood
When you create an Intent and add extras, Android stores the data in a Bundle object inside the Intent. When the target activity starts, it receives the Intent and extracts the Bundle to access the data. Parcelable objects are serialized into a flat binary format for efficient transfer. The system manages this data transfer between activities through the Android runtime.
Why designed this way?
Android uses Intents and Bundles to keep activities loosely coupled and flexible. This design allows any activity to start any other with optional data, supporting modular apps. Parcelable was created for performance over Java serialization, which was too slow for mobile devices.
┌─────────────┐
│ Activity A  │
│ (Sender)    │
└──────┬──────┘
       │ create Intent
       │ add Extras (Bundle)
       ▼
┌─────────────┐
│ Intent      │
│ (with data) │
└──────┬──────┘
       │ passed by system
       ▼
┌─────────────┐
│ Activity B  │
│ (Receiver)  │
└──────┬──────┘
       │ extract Bundle
       ▼
  Use data in UI or logic
Myth Busters - 4 Common Misconceptions
Quick: Can you pass any object directly through an intent without extra steps? Commit yes or no.
Common Belief:I can pass any custom object directly through an intent without extra work.
Tap to reveal reality
Reality:Custom objects must implement Parcelable or Serializable to be passed via intents.
Why it matters:Trying to pass unsupported objects causes crashes or data loss, breaking app functionality.
Quick: Does getStringExtra always return a non-null string? Commit yes or no.
Common Belief:getStringExtra always returns a valid string if the key exists.
Tap to reveal reality
Reality:getStringExtra can return null if the extra is missing or explicitly set null.
Why it matters:Assuming non-null causes null pointer exceptions and app crashes.
Quick: Do intent flags only affect navigation and not data passing? Commit yes or no.
Common Belief:Intent flags only control how activities open, not how data is passed or received.
Tap to reveal reality
Reality:Flags can cause activities to reuse instances, requiring data handling in onNewIntent instead of onCreate.
Why it matters:Ignoring this leads to missing or stale data and confusing bugs.
Quick: Can you send multiple pieces of data only by starting multiple intents? Commit yes or no.
Common Belief:You need a separate intent for each piece of data you want to send.
Tap to reveal reality
Reality:One intent can carry many extras at once, making data passing efficient.
Why it matters:Misunderstanding this leads to complicated and inefficient code.
Expert Zone
1
Parcelable is much faster than Serializable but requires more setup; choosing between them affects app performance.
2
Intent extras are limited in size; sending large data like images should use other methods like shared storage or databases.
3
When activities are launched in singleTop or singleTask modes, data must be handled in onNewIntent, which is often overlooked.
When NOT to use
Passing large or complex data objects through intents is not recommended; instead, use shared ViewModels, databases, or files. Also, for long-term data sharing, use persistent storage rather than intents.
Production Patterns
In real apps, developers often pass IDs or keys via intents and load full data from a database in the receiving activity. They also use Parcelable for custom objects and carefully handle lifecycle methods to manage data when activities are reused.
Connections
State Management in React
Both involve passing data between components/screens to keep UI in sync.
Understanding data passing in Android helps grasp how React components share state via props or context.
HTTP Request-Response Cycle
Intent extras are like request parameters sent to a server, and the receiving activity is like the server processing input.
Seeing intents as messages with data clarifies how client-server communication works in web development.
Human Communication
Passing data between activities is like passing notes or messages between people to share information.
Recognizing this connection helps appreciate the importance of clear, reliable data transfer in software.
Common Pitfalls
#1Crashing app by passing a non-Parcelable object directly.
Wrong approach:val intent = Intent(this, SecondActivity::class.java) intent.putExtra("user", User("Alice", 25)) startActivity(intent) // User is not Parcelable
Correct approach:@Parcelize class User(val name: String, val age: Int) : Parcelable val intent = Intent(this, SecondActivity::class.java) intent.putExtra("user", userObject) startActivity(intent)
Root cause:Not implementing Parcelable causes Android to fail serializing the object.
#2Null pointer exception when retrieving missing extras.
Wrong approach:val username = intent.getStringExtra("username")!! textView.text = username // crashes if null
Correct approach:val username = intent.getStringExtra("username") ?: "Guest" textView.text = username
Root cause:Assuming extras always exist without null checks causes crashes.
#3Missing updated data when activity is reused with flags.
Wrong approach:override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val data = intent.getStringExtra("key") // use data } // ignores onNewIntent
Correct approach:override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent?.let { val data = it.getStringExtra("key") // use data } }
Root cause:Not handling onNewIntent when activity is reused causes stale data.
Key Takeaways
Passing data between activities uses Intents carrying extras to share information between screens.
Simple data types can be passed directly, but custom objects require Parcelable implementation.
Always handle null or missing data safely to avoid crashes.
Intent flags affect activity lifecycle and data handling, requiring special attention.
In production, passing IDs and loading data separately is more efficient than sending large objects.