Alex Rivera | Logout

What about multithreading in Android SQLite?

Asked 2011-04-07T06:00:28.870
13

In my app I've got to implement some UI and Sync service. It runs in the background and updates data. Sync service is not very simple, it uses multithreading.

So, here is my story: When I started developing this app I didn't know anything about sqlite, so I just didn't use any thread synchronization in Java. Result: I got many Exceptions like "SQLiteException: database is locked: BEGIN EXCLUSIVE;"

Then I synchronized all my transactions with regular Java synchronized () {} block. Everything got much better. But I used Cursors for implementing CursorAdapter for my lists. So, sometimes I was getting the same "SQLiteException: database is locked: BEGIN EXCLUSIVE;"

I ended creating a small thread safe sqlite utility which handles all that thread-safe stuff. Also I've got to use something like ArrayAdapter (read all data from Cursor and close it after reading, also synchronize this block) for my UI. So, it is working OK

But, I don't like such way to handle UI, cause UI got really slower with this solution - reading some amount of data from cursor is rather fast, but is slower than using CursorAdapter

So, who got the solution for this question? Thank you

Edit
Report

1 Answer

20

So, finally came out to the solution. Here it is.

I read some forums, google groups and found out that sqlite database should be opened only once. So, I implemented this using singleton.

Also, I implemented some db code to synchronize all write operations (to prevent many threads execute write operations at one time). And I don't care about opening cursors, reading from them.

After some days testing I've got no error reports from my users, so I think this works

In my previous work I opened sqlite database many times across the application, that was the problem.

answered 2011-04-15T06:33:58.453

Your Answer