Skip to content Skip to sidebar Skip to footer

Oncreate Being Called On Activity A In Up Navigation

So I have an Activity A and an Activity B. I want Activity A to be able to navigate to Activity B with the press of a button. That works, but when I use the up navigation(the home

Solution 1:

This behavior is totally fine and wanted. The system might decide to stop Activities which are in background to free some memory. The same thing happens, when e.g. rotating the device.

Normally you save your instance state (like entered text and stuff) to a bundle and fetch these values from the bundle when the Activity is recreated.

Here is some standard code I use:

privateEditText mSomeUserInput;
private int mSomeExampleField;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TODO inflate layout and stuff
    mSomeUserInput = (EditText) findViewById(R.id.some_view_id);

    if (savedInstanceState == null) {
        // TODO instanciate default values
        mSomeExampleField = 42;
    } else {
        // TODO read instance state from savedInstanceState// and set values to views and private fields
        mSomeUserInput.setText(savedInstanceState.getString("mSomeUserInput"));
        mSomeExampleField = savedInstanceState.getInt("mSomeExampleField");
    }
}

@OverrideprotectedvoidonSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // TODO save your instance to outState
    outState.putString("mSomeUserInput", mSomeUserInput.getText().toString());
    outState.putInt("mSomeExampleField", mSomeExampleField);
}

Solution 2:

You can make the up button behave like pressing back, by overriding onSupportNavigateUp()

@OverridepublicbooleanonSupportNavigateUp() {
    onBackPressed();
    returntrue;
}

Solution 3:

If you want to navigate from child to parent without recreating the parent (calling onCreate method), you may set the android:launchMode="singleTop" attribute for the parent activity in your AndroidManifest.xml

Post a Comment for "Oncreate Being Called On Activity A In Up Navigation"