Best place to close database connection

According to this post by a Google engineer (Dianne Hackborn), there’s nothing wrong with leaving the database connection open:

Android made a deliberate design decision that is can seem surprising,
to just give up on the whole idea of applications cleanly exiting and
instead let the kernel clean up their resources. After all, the
kernel needs to be able to do this anyway. Given that design, keeping
anything open for the entire duration of a process’s life and never closing it is simply not a leak. It will be cleaned up when the
process is cleaned up.

So, for simplicity, I would extend the Application class to provide a single well-defined entry point for your code, and open the database connection in its onCreate(). Store the DB connection as a field in your Application, and provide an accessor method to make the connection available to rest of your code.

Then, don’t worry about closing it.

Leave a Comment