Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
We’ve seen a lot of code in this chapter, and in several places we’ve seen a reference to an app object. If you recall, this object was a reference to a DealDroidApp class when we assigned it. DealDroidApp extends Android’s Application object. An Application object has a well-defined lifecycle, and can be used as a data structure for holding an application’s global state. We’ll talk more about lifecycle in chapter 3, but the important thing to keep in mind with the Application object is that it’s created when the process for your application is created, and it isn’t bound to a particular Activity or Service. This means it’s a great and extremely simple way to hold onto and share nontrivial and nonpersistent data between activities and services within your application. By nontrivial and nonpersistent, we mean data that your application needs which would be cumbersome to pass around as Intent extras everywhere, and also isn’t appropriate for a file or database.
Another Way to Share In-App Data
Another good choice for nontrivial and nonpersistent data is a static singleton object. You have to be careful with statics, though. They don’t have a well-defined lifecycle, and it’s easy to hang onto a reference that could cause a memory leak. If you prefer statics over the Application object, that’s fine, but consider setting up and tearing down your static classes from the Application object, which does have a well-defined lifecycle, for the best of both worlds.