How can I return to a parent activity correctly?

ashiaka picture ashiaka · Sep 5, 2012 · Viewed 157.2k times · Source

I have 2 activities (A and B) in my android application and I use an intent to get from activity A to activity B. The use of parent_activity is enabled:

 <activity
        android:name=".B"
        android:label="B" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.app_name.A" />
  </activity>

I also use a theme which provides an UP-button.

So after I called activity B I can use the UP-button to get back to the activity A. The problem is that the application seems to call the onCreate()-function of activity A again and this is not the behaviour I need. I need activity A to look the same way like it looked before I called activity B.

Is there a way to achieve this?

EDIT

I didn't write any code to start activity B from activity A. I think it is auto-generated by Eclipse.

Class B looks like:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_b, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Answer

LorenzCK picture LorenzCK · Apr 10, 2013

You declared activity A with the standard launchMode in the Android manifest. According to the documentation, that means the following:

The system always creates a new instance of the activity in the target task and routes the intent to it.

Therefore, the system is forced to recreate activity A (i.e. calling onCreate) even if the task stack is handled correctly.

To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:

android:launchMode="singleTop"

Note: calling finish() (as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.