0

I'm calling Activity AddRecordActivity from Activity ViewRecordsActivity. Both extend AppCompatActivity.

I call AddRecordActivity as,

startActivityForResult(intent, Constants.MY_REQUEST_CODE);

In AddRecordActivity I call following code after adding the record:

Intent intent = new Intent(AddRecordActivity.this, ViewRecordsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Constants.EXTRA_OPERATION_SUCCESS_TEXT, "Record added");
setResult(RESULT_OK, intent);
startActivity(intent);
finish();

And in ViewRecordsActivity,

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case Constants.MY_REQUEST_CODE: {
                Toast.makeText(this, data.getStringExtra(Constants.EXTRA_OPERATION_SUCCESS_TEXT), Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}

I don't understand why the event onActivityResult is not getting triggered?

Mangesh
  • 5,491
  • 5
  • 48
  • 71

2 Answers2

5

it is because you are restarting it with startActivity(intent);. Get rid of it. Call setResult(RESULT_OK, intent); and finish(); only

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

Get rid of

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

&

startActivity(intent)

The later causes the activity to instantiate again considering it is on standard launch mode (if CLEAR_TOP flag isn't used. Otherwise the intent is delivered in onNewIntent()). Therefore, the new instance of the activity will never know you called startActivityForResult() from another instance of this activity. All you need to do is, quit the current activity by calling finish() and setResult() before finish() to achieve the desire result.

Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • *The later causes the activity to instantiate again* - the CLEAR_TOP flag prevents the reinstantiation I believe – Tim Oct 22 '15 at 09:08
  • CLEAR_TOP clears all the activities in the stack above the activity that is being launched & delivers the intent again in onNewIntent() - Yes I totally missed that @TimCastelijns Thanks for pointing that out :) – Umer Farooq Oct 22 '15 at 13:04