Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity and Background Service Access to SQLite Database

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

like image 863
NumenorForLife Avatar asked Oct 21 '22 06:10

NumenorForLife


1 Answers

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);
}
like image 118
NumenorForLife Avatar answered Oct 24 '22 05:10

NumenorForLife