Luis Mendo Luis Mendo - 2 years ago 86
Android Question

EditText not automatically saved on screen orientation change

I read that Android automatically saves the content of

objects when an application is about to be stopped or killed. However, in my app the content of an
is lost when screen orientation changes.

Is it normal behaviour? Do I then have to manually save/restore its content with
? Or is there an easier method to tell Android to save it end restore it?


I create the
object programmatically, not in XML. This turns out to be related to the problem (see accepted answer below).

Answer Source

This is not normal behavior.

First and foremost, ensure that you have IDs assigned to your EditText controls in the layout XML.

Edit 1: It just needs an ID, period. If you're doing this programmatically, it will lose state unless it has an ID.

So using this as a quick & dirty example:

    // Find my layout
    LinearLayout mLinearLayout = (LinearLayout) findViewById(;
    // Add a new EditText with default text of "test"
    EditText testText = new EditText(this.getApplicationContext());

    // This line is the key; without it, any additional text changes will 
    // be lost on rotation. Try it with and without the setId, text will revert
    // to just "test" when you rotate.


    // Add your new EditText to the view.

That will solve your problem.

Should that fail, you'll need to save and restore state yourself.

Override onSaveInstanceState like so:

protected void onSaveInstanceState(Bundle outState) {
    outState.putString("textKey", mEditText.getText().toString());

And then restore in OnCreate:

public void onCreate(Bundle savedInstanceState) {
    if(savedInstanceState != null)

Also, please don't use android:configChanges="orientation" to try to accomplish this, it's the wrong way to go.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download