开发者

Android simultaneous db operations -- "database is locked"

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 upd开发者_运维问答ate 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜