Start Activity for result

Aduait Pokhriyal picture Aduait Pokhriyal · Aug 8, 2012 · Viewed 8.9k times · Source

It may be a noob question but I have some doubt. I googled a lot but found nothing. In starting activity for result we pass request code and on result we check with the same request code and result code. I want to know Is there a way to Implement to perform different tasks and get different results from called activity by using request code i.e if the same activity is called many times with different request code then it returns different result. Please tell me how to do that. I found no way to have a switch statement or any other way to do this.

I already know the answers so editing this. I want to know If I can use the scenario like:

Intent intent = new Intent(this, yourClass.class); 
intent.putExtras(b);
if(condition1)
startActivityForResult(intent, 1);
else
startActivityForResult(intent, 2);

And my called Activity returns two differnt results for request code 1 and 2 , So I can have

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    //could replace it with a switch
    if (requestCode == 1){
        //condition 1
            }
        else if(requestCode == 2){
          //condition2
        }
}

i.e calling the same activity with different request code to get different results from the same activity.

Thanks

Answer

faizanjehangir picture faizanjehangir · Aug 8, 2012

The question posted was not so clear to me, You can always switch an activityForResult and check for activity result in onActivityResult method checking different request codes. Here is a code demonstration, how to do it:

Switch activity using this:

Intent intent = new Intent(this, yourClass.class); 
intent.putExtras(b);    // here
startActivityForResult(intent, 2); //put your code along : positive integer

Check for result in this method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    //could replace it with a switch
    if (requestCode == 1){
        //put your code here
            }
}

The called activity does not need to know your requestcode, however, if you want to do something like that, you can do that by passing your request code in intent, like this:

intent.putExtra("requestCode", requestCode); 

Hence, access the intent variable in the activity class you switched onto..