Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...