问题描述
请考虑以下内容:我有服务
,其中写入到数据库中的AsyncTask
。而我的活动读取DB(考虑简单UI线程)的数据。我访问使用DB SQLiteOpenHelper
。我创建应用的onCreate)单一实例(然后获取它的服务和活动。有没有办法,我会得到我的数据库'死锁定的可能? previously,我用的ContentProvider进行这样的操作。虽然,它是基于使用单个 SQLiteOpenHelper
情况下,我决定不包括的ContentProvider
来简化我的项目。
Consider following: I've got Service
, which writes into DB in AsyncTask
. And my Activity reads data from DB(consider UI thread for simplicity). I access DB using SQLiteOpenHelper
. I create single instance in Application onCreate() and then obtain it in service and activity. Is there any possibility that I would get my DB 'dead locked'? Previously, I used ContentProvider for such operations. Though, it is based on using single SQLiteOpenHelper
instance, I decided to simplify my project by excluding ContentProvider
.
考虑code:
public class App extends Application {
private OpenHelper openHelper;
@Override
public void onCreate(){
super.onCreate();
openHelper=new OpenHelper();
}
public OpenHelper getHelper(){
return openHelper;
}
}
在活动:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getReadableDatabase();
// Do reading
和里面的贡献莫过于,在单独的线程:
And inside Serice, in separate thread:
OpenHelper helper=(App)getApplication().getHelper();
SQLiteDatabase db=helper.getWritableDatabase();
//Do writing
难道是安全的?
Would it be safe?
UPD 这可能是解决办法,但不知道如何使用它。
UPD This might be the solution, but not sure how to use it.
推荐答案
晚了,晚了答案。你完全罚款。这是正确的方式做到这一点,其实。见我的博客文章: http://touchlabblog.tumblr.com/post/24474750219 /单sqlite的连接/ 。通过我的个人资料挖在这里。很多这样的例子。 ContentProvdier仅仅是一个很大的开销,没有必要,除非你分享你的应用程序之外的数据。交易是好加快速度和(显然)提高一致性,但没有必要的。
Late, late answer. You're totally fine. That's the proper way to do it, actually. See my blog post: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection/. Dig through my profile here. Lots of examples of this. ContentProvdier is just a lot of overhead and not needed unless you're sharing data outside of your app. Transactions are good to speed things up and (obviously) improve consistency, but not needed.
只需使用一个SqliteOpenHelper在你的应用程序,你是安全的。
Just use one SqliteOpenHelper in your app and you're safe.
这篇关于SQLite的数据库访问从多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!