When you want to start second activity use this code :
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
When you want to come back to first activity use this code :
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
And finally in the first activity you can get the returned value by the following method :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
// If there is no result
}
}
}
AN EXAMPLE :
So for using the above code for developing the example that you said :
in forst activity start second activity :
public void ButtonClickedMethod(View v)
{
Intent i = new Intent(this, Second.class);
startActivityForResult(i, 1);
}
then in the on back pressed method of second activity use this code :
@Override
public void onBackPressed()
{
Intent returnIntent = new Intent();
returnIntent.putExtra("result", ((TextView) findViewById(R.id.text)).getText());
setResult(RESULT_OK,returnIntent);
finish();
}
Again on the first activity use this code :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
((Button) findViewById(R.id.button1)).setText(result);
}
if (resultCode == RESULT_CANCELED) {
// If there is no result
}
}
}