Sunday, February 27, 2011

Handling Orientation Changes in Android

I spent a lot of time trying to figure out how to prevent my WebViews and ListViews from reloading when I changed the orientation (portrait to landscape or landscape to portrait). It is not difficult to prevent the reloading, but it involves 2 different solutions.

WebView

To prevent a WebView from reloading, add the following android:configChanges attribute as part of the WebView Activity declaration in your application AndroidManifest.xml file.




ListView

For the ListView, there were 4 code changes needed.

1. In the ListAdapters, add a method to access the data used by the Adapter.


public ArrayList... getItems()
{
return contentList;
}



2. Override the onRetainNonConfigurationInstance() method in the ListActivity classes to get the data from the ListAdapter.

@Override
public Object onRetainNonConfigurationInstance()
{
return this.adapter.getItems();
}


3. Override the onSaveInstanceState() method in the ListActivity classes. The method caches the data for the next instance of the ListActivity.

protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);

ContentCache.setObject(storedKey, content);

}



4. In the ListActivity onCreate() method, add this code, which checks to see if there is existing data before loading it again.


content = (ArrayList...)ContentCache.getObject(storedKey);
if(content==null && savedInstanceState != null)
{

content = (ArrayList...)savedInstanceState.getSerializable(storedKey);
}
if(content == null)
{
//no previous data, so RSS feed must be read
readFeed();
}
else
{
//reuse existing feed data
adapter = new LensesAdapter(currentContext, content);
setListAdapter(adapter);
}

I had to modify the ArrayList declarations because Blogger is wanting to close the part of the declaration. You can browse the source or download a zip file of the source.