Search code examples
androidandroid-intentandroid-activity

Returning intent result when Activity is closed by back button


I start a new Activity from the original Activity with startActivityForResult(intent, requestCode). I want to return data to the original Activity when the user presses the back button, so when returns to the original Activity. I tried two methods:

  • overriding onBackPressed():

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    
        Intent intent = new Intent();
        intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
        setResult(RESULT_OK, intent);
    }
    
  • overriding onPause():

    @Override
    protected void onPause() {
        super.onPause();
    
        Intent intent = new Intent();
        intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
        setResult(RESULT_OK, intent);
    }
    

Unfortunately, none of them worked (resultCode is not RESULT_OK in onActivityResult()). What's the proper way to do this? Thanks!


Solution

  • Since this question is still getting attention, i am posting a more correct answer than the one i accepted two years ago, thanks for MasterGaurav for the tip.

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putIntegerArrayListExtra(SELECTION_LIST, selected);
        setResult(RESULT_OK, intent);
    
        super.onBackPressed();
    }