Articles → Android → Return Result From Intent In Android
Return Result From Intent In Android
Example
- Add a button with the caption ‘NAVIGATE’ in MainActivity.
- On click of a button, add data in intent and navigate to SecondActivity.
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("name", "karan");
startActivityForResult(intent, 0);
- In SecondActivity, add a button with the caption ‘NAVIGATE BACK’.
- On click of the button display the text passed from MainActivity.
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
Toast.makeText(SecondActivity.this, name, Toast.LENGTH_LONG).show();
}
Click to Enlarge
- On click of ‘NAVIGATE BACK’, add the following code
@Override
public void finish() {
super.finish();
}
public void NavigateBack(View view) {
Intent intent = new Intent();
intent.putExtra("name", "Karan-Return value");
setResult(RESULT_OK, intent);
finish();
}
- In the MainActivity, add the following code
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (data != null) {
if (data.hasExtra("name")) {
Toast.makeText(this, data.getExtras().getString("name"), Toast.LENGTH_LONG).show();
}
}
}
Click to Enlarge