Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 button in the action bar) to navigate back to Activity A, onCreate() is called again and the old information that the user typed in is lost.

I've seen: onCreate always called if navigating back with intent, but they used Fragments, and I'm hoping not to have to redesign the entire app to use fragments. Is there any way I can stop onCreate() from being called every time Activity A becomes active again?

like image 344
Abe Fehr Avatar asked Oct 07 '13 02:10

Abe Fehr


2 Answers

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:

private EditText mSomeUserInput;
private int mSomeExampleField;

@Override
protected void onCreate(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");
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // TODO save your instance to outState
    outState.putString("mSomeUserInput", mSomeUserInput.getText().toString());
    outState.putInt("mSomeExampleField", mSomeExampleField);
}
like image 181
flx Avatar answered Oct 01 '22 02:10

flx


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

 @Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
like image 40
Silvia H Avatar answered Oct 01 '22 02:10

Silvia H