When building an Android app, there are times when one screen (called an activity) needs to get information from another screen. For example, a user might open a screen to select a photo or type in some details.
After the user finishes their task, the app needs to know what happened on that screen and whether the task was completed successfully. This is where RequestCode and ResultCode come in.
RequestCode and ResultCode are tools that help Android apps communicate between activities. They let the app know what kind of task is being requested and whether it was completed successfully.
What Is a RequestCode?
The RequestCode is like a tag or an identifier that tells your app what task is being requested. When you start a new activity and expect a result from it, you send a RequestCode along with the request.
The RequestCode helps your app know which request the result is related to, especially when multiple tasks are happening in the app.
For example, let’s say your app has two tasks: selecting a photo and picking a contact. Each task can have its own RequestCode:
- Selecting a photo might have a RequestCode of
1001
. - Picking a contact might have a RequestCode of
1002
.
When the result comes back, the app uses the RequestCode to figure out which task the result is for.
What Is a ResultCode?
The ResultCode is a way for the new activity (the one that handled the request) to tell the original activity whether the task was successful or not. It’s like sending a response back to the app.
There are three main ResultCodes in Android:
- RESULT_OK: This means the task was completed successfully. For example, if the user selected a photo, the app would receive this code along with the photo data.
- RESULT_CANCELED: This means the task wasn’t completed. For example, if the user changed their mind and didn’t pick a photo, the app would receive this code.
- Custom ResultCodes: Developers can also create their ResultCodes to handle specific situations.
The ResultCode helps the app know what to do next, depending on whether the task was successful or not.
How RequestCode and ResultCode Work Together
RequestCode and ResultCode work together to manage communication between activities. Here’s a simple way to understand their relationship:
- The app starts a new activity and sends a RequestCode with it. This tells the new activity what task it’s supposed to do.
- The user interacts with the new activity and completes the task (or cancels it).
- The new activity sends back a ResultCode and any additional data to the original activity.
- The original activity checks the RequestCode and ResultCode to decide what to do next.
This process ensures that the app can handle different tasks correctly, even if multiple requests are happening at the same time.
Using RequestCode and ResultCode in Android
Let’s look at an example of how to use RequestCode and ResultCode in an Android app. Imagine you’re creating an app where the user can select a photo from their gallery.
First, the app starts the gallery activity with a RequestCode. Here’s how it might look in code:
javaCopy codeIntent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1001);
Example Using startActivityForResult
(Legacy Method)
Sending the Request:
javaCopy code// Define a request code
private static final int REQUEST_CODE_EXAMPLE = 1;
// Start another activity for a result
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE_EXAMPLE);
Receiving the Result:
javaCopy code@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_EXAMPLE) {
if (resultCode == RESULT_OK) {
// Handle success
String result = data.getStringExtra("key");
Log.d("Result", result);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancellation
Log.d("Result", "Canceled");
}
}
}
Sending a Result Back:
javaCopy code// In SecondActivity, send the result back
Intent resultIntent = new Intent();
resultIntent.putExtra("key", "Some Result");
setResult(RESULT_OK, resultIntent);
finish(); // Ends the activity
Modern Alternative: Activity Result API
Using the ActivityResultLauncher
simplifies the process and is recommended in newer Android development.
Declare the Launcher:
javaCopy codeprivate ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
String resultData = data != null ? data.getStringExtra("key") : "No Data";
Log.d("Result", resultData);
} else {
Log.d("Result", "Canceled");
}
}
);
Start the Activity:
javaCopy codeIntent intent = new Intent(this, SecondActivity.class);
launcher.launch(intent);
Why RequestCode and ResultCode Are Useful
RequestCode and ResultCode make it easier to manage multiple tasks in an app. Here are some reasons why they’re important:
- They keep tasks organized. By using different RequestCodes for different tasks, the app can handle multiple requests without confusion.
- They ensure the app knows what to do next. The ResultCode lets the app decide whether to process the result or handle a cancellation.
- They make communication between activities clear. RequestCode and ResultCode provide a standard way for activities to talk to each other, reducing errors and making the app more reliable.
Best Practices for Using RequestCode and ResultCode
To use RequestCode and ResultCode effectively, here are some tips for developers:
- Use meaningful RequestCode numbers. Choose unique numbers for each task to avoid confusion. For example, you could use
1001
for photo selection and1002
contact picking. - Always check both RequestCode and ResultCode. This ensures that the app handles the correct task and responds appropriately to success or cancellation.
- Keep the
onActivityResult
method clean. If you have multiple tasks, use clear conditions and comments to make the code easy to read and maintain. - Handle errors gracefully. If something goes wrong, like the user canceling a task, make sure the app provides helpful feedback or fallback options.
How RequestCode and ResultCode Fit Into Modern Android Development
In newer versions of Android, startActivityForResult
is being replaced by the Activity Result API, which simplifies this process. However, understanding RequestCode and ResultCode is still important because many existing apps use them, and they provide a solid foundation for learning how activities communicate.
The Activity Result API removes the need for RequestCodes but retains the idea of handling results. Developers can define specific result contracts and handle them directly, making the code even cleaner.
Conclusion
RequestCode and ResultCode are essential tools for managing communication between activities in Android apps. They help apps keep tasks organized, handle results efficiently, and provide a seamless experience for users. By understanding how these codes work, developers can build apps that are both functional and user-friendly.
Whether you’re selecting a photo, picking a contact, or handling any other task, RequestCode and ResultCode ensure that your app knows what’s happening and responds correctly. As Android development evolves, these concepts remain a key part of creating smooth, interactive applications.