Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Daniel Trebbien
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):
 
Daniel Trebbien
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic