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):
Ping & DNS - updated with new look and Ping home screen widget
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.