Android的同步数据库操作 - "数据库被锁定"数据库、操作、Android、QUOT

2023-09-09 21:07:58 作者:夜闯处女村

我写有联机模式,即,数据被下载,解析并插入SQLite数据库根据需要的应用程序。所有这一切都是由服务执行。该应用程序包含了索要数据更新服务(不同的数据根据​​活动)。

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).

当用户通过活动导航(无等待服务来完成),这是很容易得到SQLiteExceptions(消息:数据库被锁定)。

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.

另一种选择可能是停止更新在每个活动的onStop方法时。当然,该更新将被中断,但是这不是一个大问题。这个问题是我不知道如何处理它。

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?

推荐答案

如果你的活动只会读,不会写像我的情况的数据库,这是我做的一个解决方法:

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

创建一个服务(即DatabaseService 0,并把它作为一个中心点来访问数据库(即打开一个数据库连接),以确保您只有一个dbhelper的时间。 在所有需要访问数据库活动和服务必须建立以DatabaseService连接 在确保只有您的下载服务的线程能够写入数据库,并应使用事务 后,您可以使用getReadable数据库中读取/使用的连接停止下载服务,等等。

只要确保你只使用1 dbhelper。

Just make sure that you only use 1 dbhelper.

 
精彩推荐
图片推荐