Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save activity state(not just some variables) on orientation change

I realized that there are lots of question on this topic already asked on SO. But I don't even know the basic when it comes to saving the state of an activity.


(Refer Screenshot Below) When app launches,

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

2) table containd data which is populated due to Gainer button.


As showed in below screenshots, While app is running in PORTRAIT mode, I

1)scrolled down to ScrollView item 4,5,6

2)pressed the Loser button so accordingly data in the table below the button changes.

3)I'll even change content of graph dynamically(which I had not done yet).


Now I switch to LANDSCAPE Mode so

1)ScrollView is showing ScrollView item 1,2,3,4

2)table is showing data which is populated due to pressing Gainer button.

3)graph is as it is as I've not changed it yet(which I will change later).


So what happens is when I change the orientation, my activity is getting re-launched. So if user is performing some task in one orientation and he changes the orientation, then whole progress will be lost.

I know I need to save the state of the activity and Restore it when orientation changes. But I don't know from where to start and what to save.

ANY HELP WILL BE LIFE-SAVER !

Scrrenshot

like image 500
GAMA Avatar asked Dec 16 '22 06:12

GAMA


1 Answers

Option #1: Override onSaveInstanceState() of your Activity and put whatever information you want in the supplied Bundle. Your new activity instance will receive that Bundle in onRestoreInstanceState() (or onCreate()). Here is a sample project demonstrating this.

Option #2: Override onRetainNonConfigurationInstance() of your Activity and return some object that represents your state. Your new activity instance can call getLastNonConfigurationInstance() to retrieve that object, so the new activity can apply that information. Be careful, though, not to have the old activity return something in the object that holds a reference back to the old activity (e.g., a widget, an instance of a regular inner class). Here is a sample project demonstrating this.

Option #3: Convert this activity to a fragment. Have the fragment call setRetainInstance(true); on itself during its initial setup. Add the fragment dynamically to some activity via a FragmentTransaction. Now, when the configuration changes, the fragment is retained, so all your widgets and state are retained. Here is an overly-complex sample application demonstrating this.

Those are the three recommended approaches nowadays.

like image 146
CommonsWare Avatar answered May 16 '23 07:05

CommonsWare