Mangesh
Mangesh

Reputation: 5841

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?

Upvotes: 0

Views: 1135

Answers (2)

Umer Farooq
Umer Farooq

Reputation: 7486

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.

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157447

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

Upvotes: 5

Related Questions