开发者

Android accessing SQLite Database from multiple threads

开发者 https://www.devze.com 2023-03-30 11:28 出处:网络
I have a SQLite Database in android that is accessed from a thread when the activity is running, 开发者_如何转开发and in the onPause() of the activity a new thread is created to save everything into t

I have a SQLite Database in android that is accessed from a thread when the activity is running, 开发者_如何转开发and in the onPause() of the activity a new thread is created to save everything into the database with a different thread to avoid timeout issues. However, when I try to do so, I either get database is locked errors. How can I fix this? Since I need to access the database from a separate thread in onPause(), could I delete somehow my previous access to it since I wouldn't use it again?


You cannot access an SQLite database when it already has a lock on it.

To avoid this, Android gives you ContentProviders to handle this sort of thing.

You should implement your own ContentProvider to do this kind of thing.

That said, databases can NEVER be assumed to be threadsafe unless you manage the threads yourself. Avoid using the db like this. Instead, cache the data (on a stack, perhaps) and request access to the database with a callback when your current transaction is complete.


As far as I know SQLite does not support concurrent access, so you either have to have a dedicated thread to provide access, or you have to obtain a lock to the SQLite object instance.

0

精彩评论

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