I'm experimenting in Android to see how to return values back to a Main Activity (coming from a child activity, Activity2), and I wanted to ask about appropriate methods.
In my Main Activity, I have a function which displays the request code and result code in a string for a proof of concept:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String a2return = "A2 reqcode: "+requestCode + "A2 result: "+resultCode;
TextView textView = findViewById(R.id.A2result);
textView.setText(a2return);
}
In my child activity, Activity2, I have the following functions which are the only ones to call the finish() function to return to Main Activity:
// "Send text back" button click
public void onButtonClick(View view) {
Intent resultIntent = new Intent();
resultIntent.putExtra("rv1", value);
resultIntent.putExtra("rv2",value+99);
setResult(Activity2.RESULT_OK, resultIntent);
finish();
}
@Override
public void onPause() {
super.onPause();
String status = "Im in PAUSE, wait a bit";
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.a2_status);
textView.setText(status);
Intent resultIntent = new Intent();
resultIntent.putExtra("rv1", value);
resultIntent.putExtra("rv2",value+99);
setResult(Activity2.RESULT_OK, resultIntent);
finish();
}
Returning back to the Main Activity via 'OnButtonClick' works correctly as expected. In Main Activity, I see appropriate codes indicating that Activity2 has finished. However, onPause does not. The onPause function is called when the user presses the back button to go back to Main Activity, the standard back button indicated in the Android Manifest.
<activity android:name=".Activity2" android:parentActivityName=".MainActivity">
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
With the way I wrote code here, it should finish the same way as OnButtonClick. Is onPause not meant to return anything when activated?
You should override onBackPressed()
rather than onPause()
for this purpose:
@Override
public void onBackPressed() {
Intent resultIntent = new Intent();
resultIntent.putExtra("rv1", value);
resultIntent.putExtra("rv2",value+99);
setResult(Activity2.RESULT_OK, resultIntent);
super.onBackPressed();
}
And for the Up navigation button in the action bar, use something like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(item));
}