Contemplating Contexts
When we call getString()
to convert a string resource into its actual String
value, we have been calling it on our MainActivity
. However, in reality, that function is implemented on Context
. MainActivity
extends AppCompatActivity
, which inherits from Activity
, which implements the Context
interface.
We use Context
objects a lot in Android.
So, in this chapter, let’s quickly review what a Context
is, where to get one, and how we use it.
It’s Not an OMG Object, But It’s Close
Back when Android was first created, in the mid-2000’s, the dominant form of Java programming was for server-side Web development, using servlets, WARs, and so on. In Web development, there is often some form of “session” object. At minimum, this object represents the user’s session with the server and represents a place where the servlet can stash values from one request that might be used in a subsequent request from the same user.
Computer programming has lots of “anti-patterns”: things that we really should not do. One of those anti-patterns is “the God object”, where we have one class that tries to do far too much. Session objects in Web development have a tendency to become God objects, because it is simple to say, “oh, well, we’ll just have the session handle that”, even for things that have little to do with maintaining user state across requests.
In Android, the God object is Context
. A lot of functionality routes through a Context
, either because:
- Our only ways of accomplishing a particular thing involve functions on a
Context
, or - Our only way to get at some other object that accomplishes that thing is by calling a function on the
Context
For lightweight app development, such as most of this book’s samples, this does not pose much of a problem. Any code in an activity, for example, has easy access to a Context
, as the activity itself is a Context
. In larger apps, though, quite a bit of time is spent trying to figure out how best to write the code to reduce the number of places where we need a Context
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.