How to use putExtra and getExtra for string data
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Android, Intent extras are the standard way to pass small pieces of data from one activity to another. For string values, the sender usually uses putExtra, and the receiver reads the same key with getStringExtra.
Put a String into an Intent
Suppose MainActivity needs to launch DetailActivity and send a username:
putExtra stores the string under a key. That key must match exactly when the receiving activity reads it.
Read the String with getStringExtra
On the receiving side:
getStringExtra returns a nullable string, so the receiver should handle the case where the extra is missing.
Why getStringExtra Is Better Than a Generic Getter
For string data, use the typed getter:
This is better than using a more generic API and casting manually, because the intent already knows how to return the right nullable type.
A Cleaner Launch Pattern
To avoid repeating keys and intent-building logic everywhere, wrap the launch step in a helper:
Then the sender uses:
This keeps the extra key private to the destination activity and reduces mistakes.
Retrieval from a Bundle
Intent extras are also accessible through the extras bundle:
This works, but getStringExtra is often clearer when you only need one string directly from the intent.
Keep Extras Small and Intentional
String extras are great for IDs, names, titles, and small configuration flags. They are not a good place to move large object graphs or entire screens of data. If the receiving activity can load its own data from an ID, passing the ID is usually cleaner.
That keeps navigation messages simple and resilient.
Common Pitfalls
The biggest pitfall is mismatched keys. If the sender uses one string constant and the receiver uses another, the extra comes back as null.
Another common mistake is assuming getStringExtra can never return null. It absolutely can, either because the extra was absent or because the activity was launched differently.
People also scatter raw string keys throughout the app. Shared constants or intent-builder helpers make this much easier to maintain.
For larger apps, that small design choice prevents subtle bugs where one activity silently looks for a slightly different key than the sender used.
It also makes it easier to define sensible defaults in the receiver, because the contract for what may or may not be present is centralized in one place.
Summary
- Use
putExtra(key, value)to attach string data to anIntent. - Read it with
getStringExtra(key)on the receiving side. - Keep the key consistent by using constants or helper methods.
- Handle
nullsafely because a string extra may be missing. - Prefer passing small values such as IDs or names instead of large payloads.
- Centralized intent-builder helpers make navigation and testing easier to maintain.

