Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call .close() on both SQLiteDatabase and SQLiteOpenHelper

Tags:

android

sqlite

SQLiteOpenHelper dbOpenHelper = new (ctx, nameofdb);
SQLiteDatabase db = dbOpener.getWritableDatabase();

Do I have to call .close() on both of these, or just one of them is enough? If yes, then which one?

SQLiteDatabase
SQLiteOpenHelper

The problem I am having is that I do not see one particular row in DDMS view in Eclipse, but when I use the Cursor to get it, it shows that I do have that entry. So I am wondering it might be caused by not closing the database properly? Anybody who can help would be great. Thanks!

like image 675
sammiwei Avatar asked Feb 03 '12 02:02

sammiwei


People also ask

What is difference SQLiteOpenHelper and SQLiteDatabase?

If it isn't already exist ofcourse. Difference between SQLiteOpenHelper and SQLiteDatabase close() is that SQLiteOpenHelper just closes inner instance of SQLiteDatabase. And it does it in thread safe way.

When should a sqlite database be closed?

Really, you don't have to close database connection. You can save database as a field in Application object. Official documentation doesn't say anything about time of database closing. Also this question quotes an old (deleted now) post of Google engineer which says, that this approach is OK.

Which two method is provide by SQLiteOpenHelper class?

SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Which method do we need to override in class SQLiteOpenHelper?

SQLiteOpenHelper provides callback methods and we should override it to get our job done. Those callback methods that we can override are onCreate(), onUpgrade(), onOpen() and onDowngrade(). And onCreate() and onUpgrade() are abstract methods and must be overridden.


1 Answers

If you look at the docs for SQLiteOpenHelper.close()...

public synchronized void close ()

Close any open database object.

It doesn't close the SQLiteOpenHelper, it closes the database.

Further to this, if you get your code right you can avoid dealing directly with the database object directly altogether.

For example, if you have a query you use regularly to get a cursor for an adapter to populate a view, create a method in your SQLiteOpenHelper class and put the query into that.

In other words, don't get a reference to the actual database in your main code just get the SQLiteOpenHelper to do everything for you.

like image 94
Squonk Avatar answered Oct 06 '22 00:10

Squonk