Android save instance state

Screen rotation typically happens once the user switches the device from portrait to landscape mode. The rotation changes cause the activity to destroy and recreate. This might affect states of some widgets that are hosted by the activity. For example, you have a ListView of one hundred items. Now the user scrolls to the middle of the ListView and rotates the screen. His/her expectation is that he/she still can see the items at the middle position of the ListView. However, this expectation is not met because the top items of the ListView display again.



One solution to the problem that you might think of is having a variable to record the scrolled position. Then, after the rotation changes you scroll the ListView to that position. But this solution does not work because the variable cannot hold its latest value after the screen rotates.
The workable solution is storing the value of the variable in the instance state object. You need to override the onSaveInstanceState method to save the variable and then override the onRestoreInstanceState method to restore the value to the variable. For the onSaveInstanceState method if it is called, it is called after the onPause() method and the onRestoreInstanceState method might be called after the onStart() method but before the onResume() method.
Now to have an example on saving instance state, you create a new project. Then in the activity_main.xml file, you add a ListView.

<ListView
     android:id="@+id/listv"
     android:layout_width= "match_parent"
     android:layout_height= "match_parent"
     android:choiceMode= "singleChoice"
     android:listSelector="#c0c0c0"
     >

     </ListView>

In the MainActivity class, you load data to the ListView using ArrayAdapter. The scrolled position must be recorded when the ListView is scrolled. So, you have to register the ListView with the OnScrollListener interface and override the onScroll() method. Then override the onSaveInstance() and onRestoreInstancestate() methods to save and restore the scrolled position across the screen rotations. In the onResume() method, you call the smoothScrollToPosition() to scroll to the position.


public class MainActivity extends Activity {

   private ListView lstV;
   private ArrayAdapter<String> adapter;
   private int scrolledPos=0;

   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     lstV=(ListView)findViewById(R.id.listv);
     String[] listItems={"Phnom Penh","Battombong","Kratie","Prey Veng","Takeo","Mondulkiri","Siem Reap","Kampong Thom","Svey Rieng"};
     adapter=new ArrayAdapter<String>(this, R.layout.list_layout, R.id.text, listItems);
     lstV.setAdapter(adapter);
    
     lstV.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
           scrolledPos=firstVisibleItem; // Record first visible row position

        }
     });

   }

   @Override
   // Save tag of the clicked button
   public void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putInt("sPos", scrolledPos);
    


   }

   @Override
   // Restore the scrolled position
   protected void onRestoreInstanceState(Bundle savedInstanceState) {
     super.onRestoreInstanceState(savedInstanceState);
     scrolledPos=savedInstanceState.getInt("sPos");
   }

   protected void onResume(){
     super.onResume();
// Scroll the ListView to the position
     lstV.smoothScrollToPosition(scrolledPos);
      
   }

}

Android-save-instance-state

Posted by: Dara | post date: 03-03-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.