1

If I have code like this

private final SQLiteDatabase database;
private final SQLiteOpenHelper helper;
// ...
this.database = helper.getWritableDatabase();
// ...

Do I need to call close() explicitly?

I am confused by this answer: https://stackoverflow.com/a/18595604/4932519

Take a look to doc for getWritableDatabase():

Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close() when you no longer need the database.)

P.S. Sorry for my English.

Community
  • 1
  • 1
xskit
  • 421
  • 1
  • 8
  • 20

1 Answers1

3

One call to close() should always be paired with every call to getWritableDatabase().

When you're calling getWritableDatabase() once for every query, you should also call close() when you've finished with the query.

When you're calling getWritableDatabase() when the activity starts up, and save the reference, you should call close() when the activity shuts down.

CL.
  • 173,858
  • 17
  • 217
  • 259
  • My answer and that answer do not contradict each other. – CL. Jan 28 '16 at 19:58
  • How about "and never explicitly close that instance"? – xskit Jan 28 '16 at 20:01
  • 1
    It will be implicitly closed eventually. Explicitly calling `close()` is more important when you're calling `getWritableDatabase()` repeatedly, because all those objects might pile up before the next garbage collection, and eat up all available file handles. – CL. Jan 28 '16 at 20:11
  • "closed eventually" using finalize method? – xskit Jan 28 '16 at 20:14
  • 1
    Yes, at the next garbage collection. – CL. Jan 28 '16 at 20:14
  • But finalize() not always called. Is not bad practice? – xskit Jan 28 '16 at 20:21
  • 1
    Yes, it's bad practice. But a single not-yet-closed database object does not matter, and the activity will be shut down only when memory is tight, so there is likely to be a garbage collection. – CL. Jan 28 '16 at 20:30
  • I've understood. Thank you again. – xskit Jan 28 '16 at 20:39