This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
When the screen orientation changes, the currently-visible Activity instance is destroyed and re-created, causing local variables of the Activity instance to be reset to their initial values. The article Global Variables in Android Apps suggests the solution of placing state data that needs to be "persisted" between instances of the activity in the app's Application object. The thing is, I don't think that I like this idea because if I program an app with multiple activities, then the Application object might become littered with variables.
A few days ago I thought about making some fields of the activity class static. Is this a good idea for storing activity state? Am I guaranteed that at most one instance of any Activity class will exist at any given time?
You can use the Activity's onRetainNonConfigurationInstance and onRestoreInstanceState methods to store and retrieve data that is needed to restore the app's state after an orientation change. Something like this (assuming that MyData contains all the instance's data/object):
Joined: Jul 10, 2007
I think that I didn't use this function because the documentation for onRetainNonConfigurationInstance says that "[I] must not rely on it being called". I'm glad that you brought it up, but I am still curious as to whether the use of static data is a good idea, or whether the most robust approach to persisting state is the use of onRetainNonConfigurationInstance and getLastNonConfigurationInstance.
Joined: Mar 22, 2005
I've never encountered a situation where the method wasn't called when the orientation changed, so I'd say it's rare enough that a full restart of the app (without any previous config data) is OK in those situations. That might be device- or manufacturer-dependent, though, so I guess it could happen more frequently on other devices - YMMV.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Best practices for storing state data "outside" of the Activity