Search code examples
androidandroid-activityviewandroid-orientation

Android screen orientation changed, textviews that are programmatically added are not saved


Basically I have two activities. The main activity has a button that goes to the second activity which specifies the name of the textview (three textviews to be specific). After that, going back the the main activity, the specified name of the textview will be displayed on the first activity but the textviews are added programmatically and is added on to different tablerows based on its name. My problem is that when the screen orientation is changed from portrait to landscape, the textviews that are programatically added are not saved. How would I save those values? I've tried android:configChanges but it doesn't save anything at all.


Solution

  • override onSaveInstanceState method and put all values you want to save. Get them back in onRestoreIntanceState method.

    UPDATED

    Save needed values

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(KEY, VALUE);
    ...
    }
    

    Restore values

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if(savedInstanceState != null){
            String str = savedInstanceState.getString(KEY);
            //Set str to your text view
        }
    }