Call Parent Activity method from Child Activity

Viewed 3680

I have Activity A that starts Activity B. Let me start by saying that I believe that Activity A can't use "startActivityForResult()" because Activity B can replace himself for another Activity B (this means, starting another activity and finishing himself), and if that happened Activity A wouldn't be expecting a result anymore and that second Activity B couldn't pass Activity A the result.

Activity A has the instance of the Model. Is there anyway I can get access to the Model from Activity B?

3 Answers

I solved this by adding into my MainActivity:

private static MainActivity main;

public static MainActivity getMain() {
    return main;
}

I am aware this is not a good practice.

you should use a layer of persistence, such as:

  • an internal database
  • Shared Preferences
  • a cloud service
  • the filesystem

...to store the state of your model types. this way that state is durable across configuration changes that result in Activity instances being recreated by Android.

In ActivityA You have to implements Serializable and using Intent. Try it.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Go to Activity B
    Intent gotoActivityB = new Intent(this, ActivityB.class);
    gotoActivityB.putExtra("ACTIVITY_A", this);
    startActivity(gotoActivityB);
}

In Activity B You can get Activity A from Intent

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    // get Activity A
    if (getIntent() != null){
        AcitivityA acitivityA = (AcitivityA) getIntent().getSerializableExtra("ACTIVITY_A");
    }
}

Sorry for my bad english :(

Related