Android simultaneous db operations — “database is locked”

时光总嘲笑我的痴心妄想 提交于 2019-12-01 23:09:48

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4302286/android-simultaneous-db-operations-database-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!