活动和后台服务访问SQLite数据库后台、数据库、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 cla...

我要检查一个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这里推荐: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);
}
阅读全文

相关推荐

最新文章