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 - and, 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 ");                   

  • 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
          protected void onActivityResult(int requestCode, int resultCode, Intent data)  
                 super.onActivityResult(requestCode, resultCode, data);  
                            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 to a texview field in . 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 . Create an edittext field to type the message and also add a button to send the message
Now you may update the like this

No comments:

Post a Comment