Reputation: 7934
To start activity for result:
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
startActivityForResult(intent,EVENT_DETAILS_REQUEST);
In my DetailsActivity, to set result and extras, that can be used in main activity:
@Override
public void onBackPressed()
{
Intent resultIntent = new Intent();
resultIntent.putExtra("isEdited",isEdited);
setResult(RESULT_OK,resultIntent);
finish();
}
Finally, in MainActivity:
@Override
protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data)
{
switch(requestCode)
{
......
case EVENT_DETAILS_REQUEST:
boolean isEdited = data.getBooleanExtra("isEdited", false);
.......
break;
}
}
This is fine as long as user is using "Back" hardware (or system navbar) button to close DetailsActivity. If user tap "Back" arrow at the top of the activity to close activity, onBackPressed
won't be called and onActivityResult
data will be null.
I have tried to use onPause
, onStop
, onFinish
instead of onBackPressed
to manage it working, but I'm getting data
for onActivityResult
always null.
What is correct way to solve my problem?
Upvotes: 3
Views: 2026
Reputation: 875
This is automatically called when hardware backpressed ..
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//your code here
return true;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 0
Reputation: 1055
You could do this to send result in all possible close cases:
@Override
public void finish() {
Intent data = new Intent();
Intent resultIntent = new Intent();
resultIntent.putExtra("isEdited", isEdited);
setResult(RESULT_OK, resultIntent);
super.finish();
}
Upvotes: 2
Reputation: 4520
Add this in your DetailsActivity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Intent resultIntent = new Intent();
resultIntent.putExtra("isEdited",isEdited);
setResult(RESULT_OK,resultIntent);
finish();
}
return super.onOptionsItemSelected(item);
}
Upvotes: 1
Reputation: 617
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Override this method in your detail activity... and this code
Upvotes: 4