Activity and Background Service Access to SQLite D

2019-03-29 11:31发布

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.

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!!

2条回答
孤傲高冷的网名
2楼-- · 2019-03-29 12:24

at onCreat in the activity put datasource.open(); then do what ever you want and at the end of actevity put this to close :

  /** Call after close activity */
@Override
protected void onStop() {
    super.onStop();
    //Close dataSource
    datasource.close();
}
查看更多
放我归山
3楼-- · 2019-03-29 12:33

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... 
} 

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

public BlacklistWordDataSource(Context context) {
    dbHelper = MySQLiteHelper.getHelper(context);
}
查看更多
登录 后发表回答