Android: does activity Waiting for activity B to complete and returns some values

I have a program that should ...

  • In Activity A complete several tasks
  • Launch Activity B (a WebView ), let the user fill in some information, then take the result
  • Then finally process the data

I have currently configured it as follows:

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 uncomfortable because I need to split the task into several different parts. I need to handle exceptions thrown in all parts, and it is inconvenient to do it this way. Is there a better way?

In addition, after step (3) above, I am going to repeat this step several times, each time sending the final result to the text view. I think that means I need to put them in AsyncTask , but that makes it even more complicated (where should I put onActivityResult ?).

+4
source share
1 answer

The simple answer: there is no other way. Here's how to do it in Android. The only thing that I think you are missing is to pass the request code to action B. Without it, you cannot distinguish which other result of the activity returned to activity A.

If you call different actions from your A, use the different requestCode parameter when using the requestCode function. Alternatively, you can pass any data back to action B using the same Intent approach (normal, 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 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 in the GUI thread, so you can do whatever updates you want right here.

Finally, in Activity B you should:

 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 process the results.

+13
source

All Articles