0
0
Android Kotlinmobile~15 mins

Passing arguments in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Passing arguments
What is it?
Passing arguments means sending information from one part of an app to another. For example, when you open a new screen, you might want to send some data to it. Arguments are like little packages of information that travel between screens or functions.
Why it matters
Without passing arguments, screens or functions would not know what data to work with, making apps less interactive and useful. Imagine trying to send a message without telling the receiver what it says. Passing arguments lets apps share data smoothly, making user experiences richer and more dynamic.
Where it fits
Before learning this, you should understand basic Kotlin syntax and how to create functions or screens (Activities/Fragments). After this, you can learn about data storage, state management, and advanced navigation techniques.
Mental Model
Core Idea
Passing arguments is like handing over a note with instructions or data when moving from one place to another in an app.
Think of it like...
It's like giving a friend a shopping list before they go to the store; the list tells them exactly what to buy.
Screen A ──> [Argument: "username = Alex"] ──> Screen B

Function call: doSomething(arg1, arg2)

┌───────────┐       ┌───────────┐
│ Screen A  │──────▶│ Screen B  │
└───────────┘       └───────────┘
   (sends data)         (receives data)
Build-Up - 6 Steps
1
FoundationWhat are arguments in Kotlin
🤔
Concept: Arguments are values you give to functions or constructors to customize their behavior.
In Kotlin, functions can take inputs called parameters. When you call a function, you pass arguments to these parameters. For example: fun greet(name: String) { println("Hello, $name!") } greet("Alex") // "Alex" is the argument passed to name
Result
The function prints: Hello, Alex!
Understanding that arguments are the actual data sent to functions helps you control what your code does each time it runs.
2
FoundationPassing arguments between Activities
🤔
Concept: You can send data from one screen (Activity) to another using Intents with extra information.
In Android, to open a new screen and send data: val intent = Intent(this, SecondActivity::class.java) intent.putExtra("username", "Alex") startActivity(intent) In SecondActivity, retrieve it: val username = intent.getStringExtra("username")
Result
SecondActivity receives the username "Alex" and can use it.
Knowing how to attach data to Intents lets you make your app interactive and responsive to user input.
3
IntermediatePassing arguments with Fragments using Bundles
🤔Before reading on: do you think Fragments receive arguments the same way as Activities? Commit to your answer.
Concept: Fragments receive arguments through a Bundle object, which is a map of key-value pairs.
To pass data to a Fragment: val fragment = MyFragment() val bundle = Bundle() bundle.putString("username", "Alex") fragment.arguments = bundle Inside MyFragment: val username = arguments?.getString("username")
Result
The Fragment can access the username "Alex" from its arguments Bundle.
Understanding Bundles as containers for arguments in Fragments helps you manage data in modular UI components.
4
IntermediateUsing Safe Args for type-safe argument passing
🤔Before reading on: do you think passing arguments with keys as strings is safe and error-free? Commit to your answer.
Concept: Safe Args is a Gradle plugin that generates code to pass arguments safely between navigation destinations, avoiding key mistakes.
With Safe Args, you define arguments in navigation XML. Then: val action = FirstFragmentDirections.actionToSecondFragment(username = "Alex") findNavController().navigate(action) In SecondFragment: val args: SecondFragmentArgs by navArgs() val username = args.username
Result
Arguments are passed with compile-time checks, reducing bugs.
Using Safe Args prevents common bugs from mistyped keys or wrong data types, making navigation safer and easier.
5
AdvancedPassing complex data with Parcelable and Serializable
🤔Before reading on: do you think you can pass any object directly as an argument between Activities? Commit to your answer.
Concept: To pass custom objects, they must implement Parcelable or Serializable interfaces to be flattened into a form Android can transfer.
Define a data class: @Parcelize data class User(val name: String, val age: Int) : Parcelable Pass it: intent.putExtra("user", userObject) Retrieve: val user = intent.getParcelableExtra("user")
Result
Custom objects are passed between screens without losing data.
Knowing how to make objects Parcelable lets you pass rich data structures, enabling complex app interactions.
6
ExpertHandling argument lifecycle and configuration changes
🤔Before reading on: do you think arguments passed once remain available after device rotation? Commit to your answer.
Concept: Arguments passed via Intents or Bundles are preserved across configuration changes, but you must handle them properly to avoid data loss.
When an Activity or Fragment is recreated (e.g., rotation), Android restores arguments automatically. However, mutable data should be saved in ViewModel or savedInstanceState to survive process death. Example: override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("username", username) }
Result
Arguments remain accessible after rotation, preventing crashes or missing data.
Understanding the lifecycle of arguments helps you build robust apps that handle device changes gracefully.
Under the Hood
When passing arguments between Activities, Android uses Intents, which are messages containing key-value pairs stored in a Bundle. This Bundle is serialized and passed to the new Activity. For Fragments, arguments are stored in a Bundle attached to the Fragment instance. Parcelable and Serializable interfaces define how objects are flattened into bytes for transfer. The Android system recreates these Bundles during lifecycle events like rotation.
Why designed this way?
Android uses Bundles and Intents to provide a flexible, standardized way to pass data between components without tight coupling. Parcelable was introduced for performance over Serializable, as it avoids reflection. This design balances ease of use, performance, and system control over component lifecycles.
┌─────────────┐       ┌───────────────┐       ┌───────────────┐
│ Activity A  │──────▶│ Intent + Bundle│──────▶│ Activity B    │
│ (sender)    │       │ (arguments)   │       │ (receiver)    │
└─────────────┘       └───────────────┘       └───────────────┘

Fragment:

┌─────────────┐
│ Fragment    │
│ arguments:  │
│ Bundle      │
└─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can you pass any Kotlin object directly as an Intent extra? Commit yes or no.
Common Belief:You can pass any Kotlin object directly as an argument between Activities.
Tap to reveal reality
Reality:Only objects implementing Parcelable or Serializable can be passed as Intent extras.
Why it matters:Trying to pass unsupported objects causes runtime crashes, breaking app flow.
Quick: Do arguments passed to a Fragment change after the Fragment is created? Commit yes or no.
Common Belief:You can change Fragment arguments anytime after creation and they will update automatically.
Tap to reveal reality
Reality:Fragment arguments are immutable after the Fragment is created; changing them has no effect.
Why it matters:Modifying arguments after creation leads to bugs where data is not updated as expected.
Quick: Are string keys for Intent extras always safe and error-free? Commit yes or no.
Common Belief:Using string keys for Intent extras is safe and cannot cause bugs.
Tap to reveal reality
Reality:String keys can be mistyped, causing missing or wrong data at runtime.
Why it matters:Mistyped keys cause silent failures that are hard to debug and degrade user experience.
Quick: Do arguments survive process death without extra handling? Commit yes or no.
Common Belief:Arguments passed via Intents or Bundles always survive process death automatically.
Tap to reveal reality
Reality:Arguments survive configuration changes but not process death; you must save state explicitly.
Why it matters:Not handling process death leads to app crashes or lost data when Android kills the app.
Expert Zone
1
Parcelable is faster than Serializable because it avoids reflection and uses manual serialization code.
2
Safe Args generates code that enforces argument types and keys at compile time, preventing runtime errors.
3
Fragments retain arguments in a Bundle that is recreated by the system, but mutable data should be stored elsewhere.
When NOT to use
Passing large data objects via arguments is inefficient; instead, use shared ViewModels, databases, or files. Avoid passing sensitive data in Intents without encryption. For complex state, consider state management libraries instead of relying solely on arguments.
Production Patterns
In production, developers use Safe Args for navigation to ensure type safety. Parcelable is preferred for custom objects. Shared ViewModels or dependency injection are used for sharing data beyond simple arguments. Arguments are kept minimal to avoid performance issues.
Connections
Function parameters and arguments
Passing arguments in mobile apps builds on the same idea as function arguments in programming.
Understanding function arguments helps grasp how data is passed between app components, as both involve sending inputs to perform tasks.
State management in React Native
Passing arguments is a simpler form of state sharing compared to centralized state management.
Knowing argument passing clarifies why apps need more advanced state tools when data sharing grows complex.
Postal mail system
Passing arguments is like sending letters with addresses and contents to recipients.
This analogy helps understand the importance of keys (addresses) and data (letters) in delivering information correctly.
Common Pitfalls
#1Trying to pass a custom object without Parcelable or Serializable.
Wrong approach:intent.putExtra("user", User("Alex", 30)) // User is a normal data class
Correct approach:@Parcelize data class User(val name: String, val age: Int) : Parcelable intent.putExtra("user", user)
Root cause:Not realizing Android requires objects to be flattened for transfer, which normal classes don't support.
#2Modifying Fragment arguments after creation expecting updates.
Wrong approach:fragment.arguments?.putString("username", "NewName") // expecting Fragment to see change
Correct approach:Create a new Bundle and set it before adding Fragment: val bundle = Bundle() bundle.putString("username", "NewName") fragment.arguments = bundle
Root cause:Misunderstanding that Fragment arguments are immutable after creation.
#3Using inconsistent string keys causing missing data.
Wrong approach:intent.putExtra("userName", "Alex") val name = intent.getStringExtra("username") // different key
Correct approach:intent.putExtra("username", "Alex") val name = intent.getStringExtra("username")
Root cause:Carelessness or typos in string keys lead to silent failures.
Key Takeaways
Passing arguments is essential for sharing data between app components like screens and functions.
Android uses Intents and Bundles to carry arguments, requiring data to be Parcelable or Serializable for custom objects.
Safe Args improves safety by generating code that prevents key and type errors during navigation.
Arguments survive configuration changes but not process death; managing state properly is crucial for robust apps.
Understanding argument passing lays the foundation for more advanced data sharing and state management techniques.