I have a class that does all the database access. It holds a reference to an SQLiteDatabase. The 30 or so functions look like this:
public boolean updateSomething(long a, int b, long c) {
ContentValues values = new ContentValues();
values.put(COL_A, a);
...
return database.update(TABLE, values, COL_ID + "=?", new String[]{id}) > 0;
}
Many StackOverflows suggest to do it like this:
public boolean updateSomething(long a, int b, long c) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_A, a);
...
boolean success = database.update(TABLE, values, COL_ID + "=?", new String[]{id}) > 0;
database.close();
return success;
}
but I also have functions that return cursors precisely because I need a cursor over the 10k rows of my database and can't just copy stuff to an array and close the database.
Others say to open the database in the onResume
and close it onPause
but that means to move the database code to the Activities or to have the database as a parameter in all these functions. Then again what do I do about AsyncTasks and other classes that run in parallel to my Activities.
My approach was to open the database in my main Activity and close it on destroy, then I realized it might be created multiple times so I counted the instances. Then I realized it might get destroyed while another Activity relies on having a database and that's where I'm stuck now. Application has no onStart/Stop callbacks that I could use to connect and close the database in.
In Android: How to close a cursor that returns from Class to Activity it is even suggested to not bother closing the database. Is that a wise move? I mean that's how I started and the LogCat got me to worry and do what is described above. What is the down side of never closing the database other than some log output?