Reference to AppCompatActivity object created via startActivity

Issue

I have got approximately this Activity construct:

MainActivity starts Activity2 startsForResult Activity3

Now I want to have the Activity result of Activity3 being send to the MainActivity.
But to create the Intent, I need to have a reference to the MainActivity.

I tried:

  • getting the reference from the intent from MainActivity to Activity2 (no method for that)
  • reusing the intent from MainActivity to Activity2 and changing the target to Activity3 (complicated and dirty)
  • making a public static reference to the MainActivity (memory leak warning)

Solution

In your MainActivity

goToNextActivity(){
    startActivityForResult(intentActivity2, SOME_REQUEST_CODE);
}

onActivityForResult(...){
    doSomeStuffWithResult();
}

In your Activity2

goToNextActivity(){
    intentActivityC = new Intent(...);
    intentActivityC.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
    startActivity(intentActivityC);
}

do not forget to use FLAG_ACTIVITY_FORWARD_RESULT in Activity2

In your Activity3

goBackToActivityA(){
    setResult(someResultCode); //setResult send the data
    finish();
}

Answered By – Vikash Parajuli

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published