Sending data back to the Main Activity in Android
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sending data back to a main activity is a normal Android pattern for pickers, settings screens, and one-off forms. The modern solution is the Activity Result API, which replaces the older startActivityForResult flow with a lifecycle-aware callback model that is easier to test and maintain.
Register a Result Launcher in the Main Activity
The main activity should register its launcher once, usually as a property, and handle the returned payload in the callback.
This keeps the request and response logic close together and avoids integer request codes.
Return Data from the Child Activity
The child activity creates a result intent, attaches extras, and finishes with RESULT_OK.
If the user backs out or cancels, call setResult(Activity.RESULT_CANCELED) or simply finish without a success result.
Pass Input into the Child Screen Too
Most result flows are not one-way. The main activity usually sends initial context, and the child returns the user's choice.
In the child activity:
Define extra keys as constants or a contract object so both sides stay aligned during refactors.
Use a Custom Contract for Reusable Flows
If the same result pattern appears in several screens, a custom ActivityResultContract is worth it. It centralizes input creation and output parsing.
This is cleaner than duplicating extra keys and parsing rules across activities.
Handle Nulls and Cancellation Explicitly
The result callback is still input-handling code, which means it should treat missing extras and cancellation as normal cases, not exceptional ones. A child activity may return RESULT_OK with incomplete data during development, or a future refactor may change a key unexpectedly.
A practical pattern is to centralize key names and branch clearly on RESULT_CANCELED, missing extras, and valid payloads. That makes activity-to-activity contracts easier to debug and test over time.
Common Pitfalls
- Registering a launcher inside a click listener instead of as part of activity setup.
- Forgetting to call
setResultbeforefinish. - Assuming the returned intent is always non-null.
- Using inconsistent extra keys between caller and child activity.
- Adding new code with deprecated
startActivityForResultwhen the Activity Result API is available.
Summary
- Use the Activity Result API for modern Android result flows.
- Return data through an intent plus an explicit result code.
- Treat the input contract and output contract as one unit.
- Use a custom contract when the same request-response flow appears in multiple places.
- Keep keys centralized so result handling stays stable during refactors.

