活动和后台服务访问SQLite数据库 [英] Activity and Background Service Access to SQLite Database

查看:274
本文介绍了活动和后台服务访问SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查一个SQLite数据库是开放的,如果是这样,我想访问一个服务类中的数据库。

I want to check if a SQLite Database is open, and if it is, I would like to access that Database within a service class.

我很担心,并已经看到,多个开放调用数据库的冲突,并抛出异常。因为我做查询我的两个活动和服务类中的数据库,我试图实施该解决方案Commonsware这里推荐:<一href="http://stackoverflow.com/questions/4842112/when-to-close-db-connection-on-android-every-time-after-your-operation-finished/4842251#4842251">When结束对Android的数据库连接?您的手术后每次完成或您的应用程序退出后。不过,我不希望在服务类中关闭再打开数据库,如果活动可能会需要它。从这个答案为什么使用SQLiteOpenHelper了SQLiteDatabase?,它看起来像它可能是有意义的实施SQLiteOpenHelper解决使得多个呼叫的问题。

I am worried, and have seen, that multiple open calls to the database clash, and throw exceptions. Because I do query the database within both my Activity and Service classes, I am attempting to implement the solution Commonsware recommended here: When to close db connection on android? Every time after your operation finished or after your app exit. However I do not want to close then open the Database within the Service class if the Activity might need it. From this answer Why use SQLiteOpenHelper over SQLiteDatabase?, it looks like it might make sense to implement a SQLiteOpenHelper to solve the issue of making multiple calls.

感谢你这么多的所有您的帮助!

Thank you so much for all your help!!

推荐答案

这人凯文是个传奇:的 http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection 。太谢谢你了。

This man Kevin is a legend: http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection. Thank you so much.

在该链接分享他可笑的简单解决方案:

On that link he shares his ridiculously simple solution:

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static DatabaseHelper instance;

    public static synchronized DatabaseHelper getHelper(Context context)
    {
        if (instance == null)
            instance = new DatabaseHelper(context);

        return instance;
    }
    //Other stuff... 
} 

然后在我的SQLite类我改变了我的code看起来是这样的:

Then in my SQLite class I changed my code to look like this:

public BlacklistWordDataSource(Context context) {
    dbHelper = MySQLiteHelper.getHelper(context);
}

这篇关于活动和后台服务访问SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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