3

Android’s Notepad tutorial Notepadv3 opens its database but never explicitly closes it. To make it correct, should Notepadv3 close its database, presumably with mDbHelper.close(); and, if so, where should that line of code appear?

Updated with a related question: The close method of NotesDbAdapter in the tutorial is implemented via mDbHelper.close(). Would it be equally effective to implement the close method via mDb.close()? In other words, is the close method of SQLiteDatabase equivalent to the close method of SQLiteOpenHelper and, if not, why is one preferred over the other?

Mike Green
  • 2,031
  • 2
  • 18
  • 16

1 Answers1

3

Yes, you should close the adapter and cursors once you don't need them anymore (for instance, when you finish your activity). That should be executed on the onDestroy method.

Cristian
  • 198,401
  • 62
  • 356
  • 264
  • 2
    Note that the reason for `onDestroy()` in this case is because the database is opened in `onCreate()`. Ideally, you should stick with the lifecycle pairs. – CommonsWare Mar 11 '11 at 17:39
  • That answer makes sense. I wonder why it wasn’t included in the tutorial example code. Since a lot of new developers to Android will use that tutorial as their starting point, they will initially miss the need to properly close the database. – Mike Green Mar 12 '11 at 13:51
  • @Mike Green, thanks for your question. Was wondering also why I get errors in LogCat with Notepad3 code. – LA_ Mar 29 '11 at 19:30
  • 1
    @LA_, yes the lack of the use of any close method to close the database in Notepadv3 causes error messages in LogCat. That is a bit disconcerting for a newcomer, who might be using the tutorial to learn to develop with Android. I don’t think the tutorial example needs to be a perfect app in every sense but it should be error free in basic areas, such as closing its database on exit. – Mike Green Mar 30 '11 at 18:02