Monday, 26 August 2013

Manage start activity for result in Android


Here is simple code to describe how to Manage start activity for result in Android. 
From your FirstActivity call the SecondActivity using startActivityForResult() method

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity, If you don't want to return back don't set any.

 In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);    
 finish();


if you don't want to return data:

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

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == 1) {
     if(resultCode == RESULT_OK){     
         String result=data.getStringExtra("result");         
     }
     if (resultCode == RESULT_CANCELED) {   
         //Write your code if there's no result
     }
  }
}
//onActivityResult