Android simultaneous db operations -- "database is locked"
Asked Answered
E

1

3

I'm writing an application with an "online mode", that is, data is downloaded, parsed and inserted into a SQLite database as needed. All this is performed by a service. The app consists of several activities that ask the service for a data update (different data depending on the activity).

When the user navigates through the activities (without waiting for the service to finish), it's very easy to get SQLiteExceptions (message: database is locked).

I thought about using synchronized blocks, but that would force the user to wait while loading a new activity (that needs database access to load) while the service finishes updating. So that seems a dead end.

Another option might be to stop the update when in the onStop method of each activity. Of course, the update will be interrupted, but that's not a big issue. Problem with this is that I'm not sure how to approach it.

My question is, how can/should I handle this?

Enrollee answered 29/11, 2010 at 9:18 Comment(0)
D
7

If your activity is only going to read and not write to database like my case, this is what i did as a workaround:

  • create a service ( i.e DatabaseService 0 and use it as a central point to access database (i.e open a database connection) to ensure you only have one dbhelper at a time.
  • all activity and service which need to access database have to establish a connection to DatabaseService
  • ensure that only your DownloadService's thread is able to write to database and it should use transaction
  • after that, you can use getReadable database to read / use the connection to stop the download service , etc.

Just make sure that you only use 1 dbhelper.

Drawplate answered 30/11, 2010 at 6:50 Comment(3)
Feeling pretty stupid (especially about the "only one dbhelper" part. I gave it a try with a singleton, because it's quicker to test, and it worked. Cheers!Enrollee
If like me you had multiple Content Providers, make the one DBhelper into Singleton.Bilow
How do you get a singleton when you need to pass a context into the constructor for SQLiteOpenHelper?Epiphragm

© 2022 - 2024 — McMap. All rights reserved.