Save activity state (and not just some variables) when changing orientation

I realized that a lot of questions have already been asked on this topic. But I donโ€™t even know the basic information about maintaining a state of activity .


(see screenshot below) When the application starts,

1) ScrollView 1,2,3,4 elements are visible

2) the table contains data that is populated due to the Gainer button.


As shown in the screenshots below, While the application is in PORTRAIT mode , I

1) scrolls to the ScrollView 4,5,6 element

2) clicked the โ€œLoserโ€ button so that the data in the table below the button changes accordingly.

3) I even dynamically change the contents of the chart (which I have not done yet).


Now I switch to LANDSCAPE mode , so

1) ScrollView shows a ScrollView element 1,2,3,4

2) the table shows the data that is populated due to pressing the Gainer button.

3) a schedule such as I have not changed (which I will change later).


So what happens when I change orientation, my activity starts up again. Therefore, if the user performs some task in one orientation, and he changes orientation, then all progress will be lost.

I know that I need to save the state of activity and restore it when the orientation changes. But I do not know where to start and what to save.

ANY HELP WILL BE LIFE NOW!

Scrrenshot

+4
source share
1 answer

Option # 1: Override onSaveInstanceState() your Activity and put any information you need into the supplied Bundle . Your new activity instance will receive a Bundle in onRestoreInstanceState() (or onCreate() ). Here is an example project demonstrating this .

Option # 2: Override onRetainNonConfigurationInstance() your Activity and return some object representing your state. Your new activity instance can call getLastNonConfigurationInstance() to retrieve this object so that the new activity can apply this information. However, be careful that the old activity does not return something in the object that references the old activity (for example, a widget, an instance of a regular inner class). Here is an example project demonstrating this .

Option # 3: convert this operation to a fragment. When calling a fragment, call setRetainInstance(true); during its initial setup. Add a fragment dynamically to some activity using FragmentTransaction . Now, when the configuration changes, the fragment is saved, so all your widgets and state are saved. This is too complex an example application demonstrating this .

Here are three recommended approaches currently.

+12
source

Source: https://habr.com/ru/post/1386796/


All Articles