5

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

Community
  • 1
  • 1
NumenorForLife
  • 1,736
  • 8
  • 27
  • 55

2 Answers2

5

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);
}
NumenorForLife
  • 1,736
  • 8
  • 27
  • 55
  • 9
    It's just a singleton code, why to be so fascinated about it? – kagali-san Jan 04 '14 at 03:29
  • 3
    A true legend doesn't worry about his (or her) critics. Anyway, the legend continues: http://kpgalligan.tumblr.com/post/109546839958/single-database-connection. Its just a collection of links on the topic. It keeps coming up. – Kevin Galligan Feb 09 '15 at 19:03
-2

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();
}
H4F
  • 131
  • 10