Home > database >  How to get result from an activity that received a new Intent
How to get result from an activity that received a new Intent

Time:12-13

I have an activity A that launches activity B for results. Activity B launches another activity C. C launches activity B again with clear top flag.

Now when I finish activity B with setResult(RESULT_OK), I receive 0 (RESULT_CANCELLED) in activity A.

How can I get the same result in activity A from B ?

CodePudding user response:

Here's one approach -

In activity B, we use startActivityForResult() to launch activity C and pass request code used to identify the result when it is returned:

// Launch activity C for a result
Intent intent = new Intent(this, ActC.class);
startActivityForResult(intent, REQUEST_CODE_C)

In activity C, we can use the setResult() method to set the result code and any data that needs to be returned to activity B when it finishes. For example:

// Set the result code and data to be returned to activity B
Intent result = new Intent();
result.putExtra(EXTRA_RESULT, resultData);
setResult(RESULT_OK, result);
// Finish activity C
finish();

then in activity B, we can implement the onActivityResult() method to handle the result when it is returned from activity C. In this method, you can use the getIntent() method to retrieve the result data:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check if the result is from activity C
    if (requestCode == REQUEST_CODE_C) {
        // Check if the result was successful
        if (resultCode == RESULT_OK) {
            // Get the result data from the intent
            String result = data.getStringExtra(EXTRA_RESULT);
        }
    }
}

CodePudding user response:

Well I eventually was able to solve the problem by consulting a friend. I was using FLAG_ACTIVITY_CLEAR_TOP only before but now I am using two flags and it resolved my issue

Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
  • Related