Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: makes activity A wait for activity B to finish and returns some values

I have a program that needs to...

  1. In Activity A, do some jobs
  2. Start up Activity B (a WebView), let user fills in some information, then collect the result
  3. Then finally process the data

Currently I set it up like this:

In Activity A:

... 
startActivityForResult(this, new Intent(ActivityB.class)); 
...

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    ...
    //get result from data, do something with it
    ...
}

This seems like an awkward approach because I need to split the task into many different parts. I need to handle the exceptions thrown in all parts and it is inconvenient doing it this way. Is there a better method?

Also, after step (3) above, I am going to repeat this step several times, each time posting the final result to a textview. I think that means I need to put them into an AsyncTask, but that makes it even more difficult (where should onActivityResult be put?).

like image 508
Tyrone Avatar asked Jun 15 '12 08:06

Tyrone


1 Answers

The simple answer is there is no other way. This is how it's mean to be done in Android. The only thing, I believe, you're missing is passing a request code to activity B. Without it, you wouldn't be able to differentiate which other activity returned result to activity A.

If you're invoking different activities from your A, use different requestCode parameter when starting activity. Furthermore, you can pass any data back to activity B using the same Intent approach (ok, almost any):

public final static int REQUEST_CODE_B = 1;
public final static int REQUEST_CODE_C = 2;
...

Intent i = new Intent(this, ActivityB.class);
i.putExtra(...);    //if you need to pass parameters
startActivityForResult(i, REQUEST_CODE_B);

...

//and in another place:
Intent i = new Intent(this, ActivityC.class);
i.putExtra(...);    //if you need to pass parameters
startActivityForResult(i, REQUEST_CODE_C);

Then in your on ActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case REQUEST_CODE_B:
            //you just got back from activity B - deal with resultCode
            //use data.getExtra(...) to retrieve the returned data
            break;
        case REQUEST_CODE_C:
            //you just got back from activity C - deal with resultCode
            break;
    }
}

OnActivityResult is executed on the GUI thread, therefore you can make any updates you want straight in here.

Finally, in Activity B, you'd have:

Intent resultIntent = new Intent();
resultIntent.putExtra(...);  // put data that you want returned to activity A
setResult(Activity.RESULT_OK, resultIntent);
finish();

I'm not sure why you need AsyncTask to handle results.

like image 147
Aleks G Avatar answered Nov 11 '22 21:11

Aleks G