aspose file tools*
The moose likes Android and the fly likes Best practices for storing state data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Mobile » Android
Bookmark "Best practices for storing state data "outside" of the Activity" Watch "Best practices for storing state data "outside" of the Activity" New topic
Author

Best practices for storing state data "outside" of the Activity

Daniel Trebbien
Ranch Hand

Joined: Jul 10, 2007
Posts: 57
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?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42639
    
  65
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 - my free Android networking tools app
Daniel Trebbien
Ranch Hand

Joined: Jul 10, 2007
Posts: 57
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.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42639
    
  65
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Best practices for storing state data "outside" of the Activity