Getting a Result from an Activity in Android

When we open a new activity from an activity itself, we can send data to it by using an intent and putExtra() method. But what if we also want to get something back? This is what the startActivityForResult() method is for. By opening our child activity with this method and overriding onActivityResult() we can send data back to our parent activity after we set it with setResult() in our child activity before we close it.

Step 1 — Starting a new activity for result

MainActivity.javaint REQUEST_CODE = 1;
Intent intent = new Intent(MainActivity.this, ChildActivity.class);
intent.putExtra("number1", number1);
intent.putExtra("number2", number2);
startActivityForResult(intent, REQUEST_CODE);

We need the REQUEST_CODE to identify the request as we can open any number of child activities for result and filter the results based on this value.

Step 2 — Setting the result in child activity

ChildActivity.java// perform some operation in child activitybuttonAdd.setOnClickListener(new View.OnClickListener() @Override
public void onClick(View v) int result = number1 + number2;
Intent resultIntent = new Intent();
resultIntent.putExtra("result", result);
setResult(RESULT_OK, resultIntent);
finish();
>>);

The method setResult(resultCode, data) sends back the data along with result code. We set the RESULT_CODE = 1 (RESULT_OK) for success. If we don’t call this method RESULT_CODE = -1 (RESULT_CANCELED).

Step 3 — Getting the result in parent activity

MainActivity.java@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) if (resultCode == RESULT_OK) int result = data.getIntExtra("result", 0);
mTextViewResult.setText("" + result);
>
if (resultCode == RESULT_CANCELED) mTextViewResult.setText("Nothing selected");
>
>
>

And in these 3 steps, you get the data back from a child activity to the parent activity using startActivityForResult() method.

I hope you learned something! Thank you for reading.

Click the 👏 to show your support and share it with other fellow Medium users.