Android Development
startActivityForResult
Mobile App Development
Android Intents
Android Programming

How to manage startActivityForResult on Android

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding startActivityForResult

Managing results from activities in Android is a common task for developers. The startActivityForResult method has been a cornerstone for handling this inter-activity communication. It allows you to start another activity and receive a result back when it finishes. However, with the advent of more simplified and efficient tools like the "Activity Result APIs," the usage of startActivityForResult has evolved. Below, we will dive deep into its workings, technical implementations, and best practices.

Basic Workflow of startActivityForResult

  1. Initiating the Activity: You start by calling startActivityForResult from the sending activity. You must provide an Intent and a unique request code.
  2. Defining the Target Activity: The target activity will process the request and pack the result into an Intent. It will then call setResult with the result and the Intent.
  3. Processing the Result: The sending activity overrides the onActivityResult method to handle the data returned from the target activity.

Example Workflow

Let's consider a simple example to clarify these steps.

Sending Activity (Activity A)

Activity A wants to get some data from Activity B:

java
1public static final int REQUEST_CODE = 1;
2
3@Override
4protected void onCreate(Bundle savedInstanceState) {
5    super.onCreate(savedInstanceState);
6    setContentView(R.layout.activity_main);
7
8    // Create an Intent to start Activity B
9    Intent intent = new Intent(this, ActivityB.class);
10    startActivityForResult(intent, REQUEST_CODE);
11}
12
13@Override
14protected void onActivityResult(int requestCode, int resultCode, Intent data) {
15    super.onActivityResult(requestCode, resultCode, data);
16    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
17        if (data != null) {
18            // Extract data from the result
19            String result = data.getStringExtra("resultKey");
20            // Proceed with the result
21        }
22    }
23}

Target Activity (Activity B)

Activity B will send results back to Activity A:

java
1@Override
2protected void onCreate(Bundle savedInstanceState) {
3    super.onCreate(savedInstanceState);
4    setContentView(R.layout.activity_b);
5
6    // Set any data that you want to pass back
7    String resultData = "This is a result";
8    Intent resultIntent = new Intent();
9    resultIntent.putExtra("resultKey", resultData);
10
11    // Use setResult to return the result
12    setResult(RESULT_OK, resultIntent);
13    // Finish the Activity B to return the result
14    finish();
15}

Points to Consider

  • Request Code: Ensure that each request code is unique to differentiate among multiple result intents.
  • Result Code: Standard Android result codes are RESULT_OK and RESULT_CANCELED, but custom codes can be useful for more detailed status information.
  • Null Checks: Always perform null checks when accessing data from the returning Intent to avoid NullPointerException.

Transition to Activity Result APIs

With the adoption of Android's Activity Result APIs, developers are encouraged to use this more robust method, as startActivityForResult is considered deprecated in some contexts. This API simplifies the result handling and avoids the boilerplate of maintaining request codes.

Example Using Activity Result APIs

java
1// Define a launcher at the top scope of your activity
2private ActivityResultLauncher<Intent> resultLauncher = 
3    registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
4    new ActivityResultCallback<ActivityResult>() {
5        @Override
6        public void onActivityResult(ActivityResult result) {
7            if (result.getResultCode() == Activity.RESULT_OK) {
8                Intent data = result.getData();
9                // Handle your data
10            }
11        }
12    });
13
14@Override
15protected void onCreate(Bundle savedInstanceState) {
16    super.onCreate(savedInstanceState);
17    setContentView(R.layout.activity_main);
18
19    // Use the launcher to start Activity B
20    Intent intent = new Intent(this, ActivityB.class);
21    resultLauncher.launch(intent);
22}

Advantages of Activity Result APIs

  • No Request Codes: Simplifies management by eliminating the need for unique request codes.
  • Modularity: Encapsulates result handling logic in one place for easier code management.
  • Type Safety: Reduces type-related bugs by providing type-safe contracts.

Key Differences and Comparison

FeaturestartActivityForResultActivity Result APIs
Request CodesRequiredNot Required
SetupOverriding onActivityResultRegistering a launcher
Error HandlingManual null checks & castingType-safe handling
API LevelAll Android VersionsRecommended from API 23 onwards
ModularizationCan be verbose; logic dispersedEncapsulated logic

Conclusion

While traditional methods using startActivityForResult have provided a solid foundation for activity results management in Android, transitioning to Activity Result APIs offers a cleaner, more efficient approach. Adaptation of new methods in Android development can lead to more maintainable and less error-prone code. Always refer to Android's documentation and guidelines to stay updated with best practices and API changes.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.