Search code examples
androidandroid-intentonactivityresult

android - onActivityResult not called


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?


Solution

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