Chapter 14 SQLite Databases
For the More Curious: The Application Context
Earlier in this chapter, you used the application context in the constructor of the CrimeLab.
private CrimeLab(Context context) {
mContext = context.getApplicationContext();
}
What makes the application context special? When should you use the application context over an
activity as a context?
It is important to think about the lifetime of each of these objects. If any of your activities exist,
Android will have also created an application object. Activities come and go as the user navigates
through your application, but the application object will still exist. It has a much longer lifetime than
any one activity.
The CrimeLab is a singleton, which means that once it is created, it will not be destroyed until your
entire application process is destroyed. Also, the CrimeLab maintains a reference to its mContext
object. If you store an activity as the mContext object, that activity will never be cleaned up by the
garbage collector because the CrimeLab has a reference to it. Even if the user has navigated away from
that activity, it will never be cleaned up.
To avoid this wasteful situation, you use the application context so that your activities can come and
go and the CrimeLab can maintain a reference to a Context object. Always think about the lifetime of
your activities as you keep a reference to them.
Challenge: Deleting Crimes
If you added a Delete Crime action item earlier, this challenge builds off of that by adding the ability to
delete crimes from your database by calling a deleteCrime(Crime) method on CrimeLab, which will
call mDatabase.delete(...) to finish the job.
And if you do not have a Delete Crime? Well, go ahead and add it! Add an action item to
CrimeFragment’s toolbar that calls CrimeLab.deleteCrime(Crime) and finish()es its Activity.