startactivityforresult example in android



startActivityForResult method helps to send data to another activity, get data from another activity or even wait for the result from another activity to perform certain action/ process the result data.

The process involved are,

  • Consider there are two activities - MainActivity.java and SecondActivity.java, the main activity calls the second activity and waits for the result like shown below, 
Intent intent=new Intent(MainActivity.this,SecondActivity.class);       
startActivityForResult(intent, 2);

  •  Now the SecondActivity performs the required operations(if any) and returns the result like shown below
Intent intent=new Intent();      
intent.putExtra("MESSAGE","your message to FirstActivity ");                   
setResult(2,intent);

  • Now we should override the onActivityResult method inside MainActivity which gets automatically invoked once the results from the SecondActivity are returned. It is overidden like shown below
          @Override  
          protected void onActivityResult(int requestCode, int resultCode, Intent data)  
          {
                 super.onActivityResult(requestCode, resultCode, data);  
                   if(requestCode==2)  
                         {
                            String message=data.getStringExtra("MESSAGE");   
                         }
          }  

  • Finally you can now access the message send from the SecondActivity using the  String "message" 
Now let us look into a working example. In this example, we will be passing a message from an editext field inside the SecondActivity.java to a texview field in MainActivity.java . So first of all create a new android studio project and make the following changes to your activity_main.xml file
As shown above we have created a button to call the second activity and also added a textview to display the result from second activity. Now we need to call the second activity and wait for result as shown below :
As shown above we have used startActivityForResult to start the second activity so that we we will get the result from the second activity in the callback method - onActivityResult
Now create new activity and name it as SecondActivity.java . Create an edittext field to type the message and also add a button to send the message
Now you may update the SecondActivity.java like this

No comments:

Post a Comment