I also have multiple Activities and each Activity opens its own database connection. I keep the main Activity alive while I start other activities, and I call finish() on the child activities when I no longer need them.
What I am seeing is that a child Activity can successfully open a connection and query data while the main Actitity is still holding on to its DBAdapter. When the child Activity ends, the main Activity requeries any cursors that are open. This seems to happen automatically.
However, after clicking around on the user interface for a while, which causes my app to start and finish Activities, I will eventually get the exception:
ERROR/Database(17657): Leak found
ERROR/Database(17657): java.lang.IllegalStateException:
/data/data/yourpackage/databases/yourdatabase
SQLiteDatabase created and never closed
ERROR/Database(17657): at android.database.sqlite.SQLiteDatabase.<init>
(SQLiteDatabase.java:1694)
The exception is not from the Activity that is currently in the foreground, but from one that was finished a while ago. So, what happens is that the garbage collector is cleaning up and finding the open database connection. This does not affect the app - it continues to work fine and all queries from the foreground Activity return data.
The solution is simply to close the connection in the child Activity. The onDestroy() event is the right place to do that:
@Override
protected void onDestroy() {
super.onDestroy();
myAdapter.close();
}
Since I put this in all my child Activities, I no longer get the exception.