Wednesday, 28 August 2013

How to start an activity waiting for results

In Android the intents are uses to starts a new activity. Sometimes, the new activity starts because the app is waiting to the user to perfom some action in order to get an input. For those type of activities, the method startActivityForResult() should be used instead of startActivity.

This method has two parameters: The intent to start the activity itself and an numerical id. The numerical id allow the app to classify the content received if in the same activity there are several calls to startActivityForResult.

1. Basic usage
In the first activity, add the follow code to start the second activity.

private static final int SECOND_ACTIVITY_ID = 1;
Intent startSecondActivityIntent = new Intent(this, SecondActivity.class);
startActivityForResult(startSecondActivityIntent, SECOND_ACTIVITY_ID);

In the second activity, when the data is ready, use the follow code to send back the data:

public static final String RESULT_KEY = "result";
Intent returnIntent = new Intent();
returnIntent.putExtra(RESULT_KEY, result);
setResult(RESULT_OK, returnIntent);

At this point there is not need to start the first activity explicitly. When the second activity finishes, the first activity will be brought to the foreground.

After it, the method onActivityResult of the first activity will be called, The app must override the method in order to get the result.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SECOND_ACTIVITY_ID) {
        if (resultCode == RESULT_OK) {
            String result = data.getStringExtra(SecondActivity.RESULT_KEY);

        if (resultCode == RESULT_CANCELED) {
            // No result found

2. If there are some problem
If there is any problem in the second activity, then the resultCode RESULT_CANCELED could be used in the second activity.

Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);

StackOverflow - Android, How to manage start activity for result?

No comments:

Post a Comment