Example B: This example will be almost the same as in our first "example A" article, with the main difference that we need to get information back from the new Activity opened. This example will be different: We are creating a shopping list, in an Activity we have the product list (product name, price, product code), and we open a new Activity with a form to introduce the new product, when we press “enter” we go back to the products list and a new product is added (the one we have added in the previous Activity).
After calling the new Activity (the form one, lets call it FormActiviy) we need to add a method in the main Activity (lets call this ProductActivity), this method will receive the data from the FormActivity and here we will do whatever we want with this info.
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
}
Perhaps we also want to receive information from more than one Activity, that's what we can gather here by checking the resultCode. The resultCode gives us information about which Activity has been opened and gives us the result.
To call the FormActivity we have to do it in this way.
Intent intent = new Intent("com.bright.hub.package.FormActivity");
startActivityForResult(intent, RESULT_CODE_CONSTANT);
We create an Intent calling to the Activity, in this case the FormActivity, and we start the new Activity with the startActivityForResult, with this we are saying that we are expecting a response from the FormActivity.
In the FormActivity, once we have accomplished the task it was made for, and we want to go back, we use the following lines:
Intent i = new Intent();
i.putExtra(“NAME”,object.name);
I.putExtra(“KIND”,object.kind);
...
setResult(RESULT_CODE_CONSTANT, i);
We create a new intent, we add to this intent the information we want to return back to the ProductActivity, and then we call to the setResult method adding the RESULT_CODE_CONSTANT that we are going to receive in the ProductActivity.
This way in the onActivityResult we can obtain the info using the “data” intent from this method.