Search code examples
androidandroid-savedstate

Android doesn't automatically save view states


Basically, I have a TextView and two EditText views in one activity. From that activity, a different activity is started. If I press the hardware back button on the device (ending the second activity), the views' states are the same as before, which is good. However, after pressing the back button on the action bar (of the second activity), the views lose their previous state.

According to the docs, if you provide an ID for your views (widgets such as EditText, TextView, etc), android will automatically save their state.

For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required of you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

I have a unique id for each view that needs its state saved. I've also tried explicitly using android:saveEnabled="true" in XML and textView.setSaveEnabled(true); to no avail.

I've tried implementing onSaveInstanceState and onRestoreInstanceState and calling super first thing for both. onSaveInstanceState is called as expected, but onRestoreInstanceState is never called. Also, savedInstanceState passed to onCreate is always null.

In the manifest, I've tried android:alwaysRetainTaskState="true" and android:stateNotNeeded="false" with no luck.

I can post code, but I'm not sure what code would be relevant since the system doesn't seem to be doing what it's supposed to. What possible thing could cause the views' states to not be auto-saved by android? Any help is appreciated and I can post specific code if needed.

Sidenote: I'm using AppCompat if it makes any difference.


Solution

  • Try using:

        <activity
            android:name=".MyActivity"
            android:label="@string/activity_title"
            android:launchMode="singleTop"
            android:parentActivityName=".MyActivityParent">
        </activity>
    

    Note the android:launchMode="singleTop" attribute.

    By default, when the user presses the Back button, a new Intent is created, and your Activity is recreated from scratch. Setting the launchMode attribute in this way tells the ART to preserve and reuse the instance of your Activity.