【问题标题】:Activity and Background Service Access to SQLite Database对 SQLite 数据库的活动和后台服务访问
【发布时间】:2013-06-27 16:35:20
【问题描述】:

我想检查 SQLite 数据库是否打开,如果打开,我想在服务类中访问该数据库。

我担心并且已经看到对数据库的多次打开调用会发生冲突并引发异常。因为我确实在我的 Activity 和 Service 类中查询了数据库,所以我正在尝试实现这里推荐的 Commonsware 解决方案:When to close db connection on android? Every time after your operation finished or after your app exit。但是,如果活动可能需要它,我不想在服务类中关闭然后打开数据库。从这个答案Why use SQLiteOpenHelper over SQLiteDatabase? 看来,实现一个 SQLiteOpenHelper 来解决进行多次调用的问题可能是有意义的。

非常感谢您的帮助!!

【问题讨论】:

    标签: android sqlite android-activity android-service android-sqlite


    【解决方案1】:

    这个人凯文是一个传奇:http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection。非常感谢。

    在那个链接上,他分享了他非常简单的解决方案:

    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 类中,我将代码更改为如下所示:

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

    【讨论】:

    • 这只是一个单例代码,为什么对它如此着迷?
    • 真正的传奇人物不会担心他(或她)的批评者。无论如何,传奇仍在继续:kpgalligan.tumblr.com/post/109546839958/…。它只是有关该主题的链接的集合。它不断出现。
    【解决方案2】:

    在活动中的 onCreat 中放入 datasource.open(); 然后做任何你想做的事 并在活动结束时将其关闭:

      /** Call after close activity */
    @Override
    protected void onStop() {
        super.onStop();
        //Close dataSource
        datasource.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      相关资源
      最近更新 更多