Android的同步数据库操作 - "数据库被锁定" [英] Android simultaneous db operations -- "database is locked"

查看:148
本文介绍了Android的同步数据库操作 - "数据库被锁定"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写有联机模式,即,数据被下载,解析并插入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.

这篇关于Android的同步数据库操作 - "数据库被锁定"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆