Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing SQLite Connections in Android

I have a (hopefully) quick question regarding handling SQLite database connections in Android. I have an app that is composed, naturally, of several activities. I have no trouble creating/updating/querying the database, as I've created a single, dedicated class to handle that work via SQLiteOpenHelper, etc.

My question is this: since these activities all share this same database, is this usually implemented as a single, static member, or should each activity own its own connection? My concern of course is the cost of re-connecting to the database in each activity.

Or, put another way, is there any reason not to just store a singleton instance?

I'm also wondering if there's something going on behind the scenes similar to .NET's connection pooling to reduce the cost of opening connections.

Thanks in advance!

like image 921
Nathan B Avatar asked Mar 01 '11 14:03

Nathan B


People also ask

How many connections can SQLite handle?

The default limit is 1,024.

Can SQLite handle multiple connections?

SQLite does support multiple concurrent connections, and therefore it can be used with a multi-threaded or multi-process application. The catch is that when SQLite opens a write transaction, it will lock all the tables.


2 Answers

Connection opening in SQLite is about 0.2ms.

The best practice tells us to open and close the connection each time we need one.

like image 152
Vladimir Ivanov Avatar answered Sep 22 '22 04:09

Vladimir Ivanov


Just use SQLiteOpenHelper.getReadableDatabase() and SQLiteOpenHelper.getWriteableDatabase() - Android will manage and cache the connection so you don't need to.

In fact, refer to the official Google Using Databases documentation:

To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase

like image 37
RivieraKid Avatar answered Sep 21 '22 04:09

RivieraKid