Search code examples
androidandroid-studioandroid-intentandroid-activityandroid-context

Reference to AppCompatActivity object created via startActivity


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();
    }