Bird
Raised Fist0
Android Kotlinmobile~15 mins

Passing arguments in Android Kotlin - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the primary purpose of passing arguments between activities in Android Kotlin?
easy
A. To close the current activity
B. To change the app theme
C. To share data between different screens
D. To update the app version

Solution

  1. Step 1: Understand activity communication

    Activities often need to share information like user input or selections.
  2. Step 2: Purpose of passing arguments

    Passing arguments allows one screen to send data to another screen.
  3. Final Answer:

    To share data between different screens -> Option C
  4. Quick Check:

    Passing arguments = sharing data [OK]
Hint: Passing arguments means sending data between screens [OK]
Common Mistakes:
  • Thinking it changes app theme
  • Confusing with app version updates
  • Assuming it closes activities
2. Which Kotlin code correctly passes a String argument "username" with value "Alice" to another activity using Intent?
easy
A. val intent = Intent(this, NextActivity::class.java) intent.putExtra("username", "Alice") startActivity(intent)
B. val intent = Intent(this, NextActivity::class.java) intent.putString("username", "Alice") startActivity(intent)
C. val intent = Intent(this, NextActivity::class.java) intent.addExtra("username", "Alice") startActivity(intent)
D. val intent = Intent(this, NextActivity::class.java) intent.setExtra("username", "Alice") startActivity(intent)

Solution

  1. Step 1: Identify correct Intent method

    The method to add data is putExtra(key, value).
  2. Step 2: Check method names in options

    Only val intent = Intent(this, NextActivity::class.java) intent.putExtra("username", "Alice") startActivity(intent) uses putExtra correctly; others use invalid method names.
  3. Final Answer:

    val intent = Intent(this, NextActivity::class.java)\nintent.putExtra("username", "Alice")\nstartActivity(intent) -> Option A
  4. Quick Check:

    Use putExtra() to pass data [OK]
Hint: Use putExtra() to add data to Intent [OK]
Common Mistakes:
  • Using non-existent methods like putString or addExtra
  • Forgetting to call startActivity()
  • Passing wrong argument types
3. What will be the output of the following code in the receiving activity?
val username = intent.getStringExtra("username")
textView.text = username ?: "Guest"
If the sending activity did NOT pass any "username" extra?
medium
A. The app will crash with NullPointerException
B. The TextView will show "null"
C. The TextView will be empty
D. The TextView will show "Guest"

Solution

  1. Step 1: Understand getStringExtra behavior

    If no extra is passed, getStringExtra returns null.
  2. Step 2: Analyze Elvis operator usage

    The expression username ?: "Guest" means if username is null, use "Guest".
  3. Final Answer:

    The TextView will show "Guest" -> Option D
  4. Quick Check:

    Null fallback with ?: operator = "Guest" [OK]
Hint: ?: operator provides default if null [OK]
Common Mistakes:
  • Expecting null string to display
  • Assuming app crashes on null
  • Forgetting ?: fallback
4. Identify the error in this code snippet that tries to retrieve an Int extra named "age":
val age = intent.getIntExtra("age")
textView.text = age.toString()
medium
A. getIntExtra requires a default value as second argument
B. getIntExtra should be getIntExtras
C. age.toString() is invalid for Int
D. Intent cannot carry Int values

Solution

  1. Step 1: Check getIntExtra method signature

    getIntExtra requires two arguments: key and default value.
  2. Step 2: Identify missing argument

    The code misses the default value argument, causing a compile error.
  3. Final Answer:

    getIntExtra requires a default value as second argument -> Option A
  4. Quick Check:

    getIntExtra(key, default) needs default [OK]
Hint: Always provide default value for getIntExtra [OK]
Common Mistakes:
  • Omitting default value argument
  • Using wrong method name getIntExtras
  • Thinking Int can't be passed
5. You want to pass a list of Strings named "items" from one activity to another. Which is the correct way to pass and retrieve this list using Intent?
hard
A. Use intent.putExtra("items", items) and intent.getStringExtra("items")
B. Use intent.putStringArrayListExtra("items", items) and intent.getStringArrayListExtra("items")
C. Use intent.putExtra("items", items.toString()) and intent.getStringExtra("items")
D. Use intent.putExtra("items", items) and intent.getSerializableExtra("items")

Solution

  1. Step 1: Passing a list of Strings

    For ArrayList<String>, use putStringArrayListExtra to pass the list.
  2. Step 2: Retrieving the list

    Use getStringArrayListExtra to get the list back safely.
  3. Final Answer:

    Use intent.putStringArrayListExtra("items", items) and intent.getStringArrayListExtra("items") -> Option B
  4. Quick Check:

    Use put/getStringArrayListExtra for String lists [OK]
Hint: Use put/getStringArrayListExtra for String lists [OK]
Common Mistakes:
  • Passing list as plain putExtra
  • Converting list to string incorrectly
  • Using getSerializableExtra without casting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard