How to return a result startActivityForResult from a TabHost Activity?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Android development, startActivityForResult
is a mechanism that allows you to start a new activity and receive results from it when the activity finishes. This pattern is commonly used when you need to retrieve data back from an activity—for example, when picking a contact or capturing a photo.
Using startActivityForResult
with a TabHost
can be a bit more complex compared to using this mechanism with standalone activities. This article covers the technical explanation and implementation of returning a result from a TabHost
activity with examples and additional context.
Understanding TabHost
and startActivityForResult
Overview of TabHost
TabHost
is a UI component that organizes activities or fragments into tabs. Each tab can display a different activity, allowing users to switch between multiple activities within a single screen. Although TabHost
is largely deprecated in favor of more flexible navigation components (like ViewPager
with TabLayout
), it's still beneficial to understand it if you're working on maintaining older projects or learning fundamental Android concepts.
Overview of startActivityForResult
startActivityForResult
is a method used to start another activity with the expectation that the activity will return data. This is done by calling setResult(int, Intent)
before finish()
in the launched activity:
- Intent: Used to start the activity.
- Request Code: An integer code to identify the activity.
- Result Code: A code returned by the activity to indicate success or failure.
- Data Intent: An Intent carrying the result data.
Key Methods
startActivityForResult(Intent intent, int requestCode)setResult(int resultCode, Intent data)onActivityResult(int requestCode, int resultCode, Intent data)
Implementing startActivityForResult
with TabHost
To use startActivityForResult
within TabHost
, we must be careful about request and result processing, especially since multiple tab activities might be involved. The challenge is effectively routing the result back to the correct activity encapsulated within a tab.
Step-by-Step Implementation
1. Setting Up TabHost
- Lifecycle Management: Properly managing the lifecycle of both host activities and tab activities is crucial to avoid leaks or crashes.
- Deprecation: Keep in mind that
TabHostis deprecated, and newer implementations usingViewPagerandTabLayoutwith fragments are recommended.

