user1209216
user1209216

Reputation: 7934

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?

Upvotes: 3

Views: 2026

Answers (4)

Omar Dhanish
Omar Dhanish

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

user3161880
user3161880

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

Vinayak B
Vinayak B

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

Manoj Bhadane
Manoj Bhadane

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

Related Questions