Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - set activity result on activity closed

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?

like image 955
user1209216 Avatar asked Mar 14 '26 00:03

user1209216


2 Answers

@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

like image 176
Manoj Bhadane Avatar answered Mar 15 '26 12:03

Manoj Bhadane


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();
}
like image 41
user3161880 Avatar answered Mar 15 '26 13:03

user3161880



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!