user1219278
user1219278

Reputation: 1909

Keeping a global reference to SQLiteDatabase?

I'm using a single sqlite database throughout my app. So I want to wrap a connection to the db in a singleton for convenience. At first I thought I could keep a reference to the SQLiteDatabase around for that:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // local
myGlobalSQLiteDatabase = helper.getWritableDatabase(); // global

...

void someFunction() {
    try {
        myGlobalSQLiteDatabase.insertOrThrow(...);
    } catch (Exception ex) {
    }
}

but this would result in errors such as:

(1802) os_unix.c:30011: (2) stat(/data/data/com.me.test/databases/test.db) - 
(1802) statement aborts at 16: [INSERT INTO mytable(f1,f2) VALUES (?,?)]
android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 1802)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
    ...

(this is all being done on the main thread, a single test).

My second attempt was to instead keep a global reference to the helper only:

myGlobalSQLiteOpenHelper helper = new MySQLiteOpenHelper(appContext); // global

...

void someFunction() {
    SQLiteDatabase db = myGlobalSQLiteOpenHelper.getWritableDatabase();
    try {
        db.insertOrThrow(...);
    } catch (Exception ex) {
    } finally {
        db.close();
    }
}

and that works. I have to call getWritableDatabase() and close() on each call of someFunction().

I don't know how much overhead there is in getWritableDatabase() and close(), I was originally hoping for the fastest implementation possible, as I'll be calling someFunction() repeatedly in response to user input. Is the second method the best option for this setup?

Thanks

Upvotes: 1

Views: 1005

Answers (1)

Sammar javed
Sammar javed

Reputation: 153

You don't need to write getwritable database again and again just make a constructor of db class public DBCustomer open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } and call all the function of db just decalring object and calling object.open function

Upvotes: 1

Related Questions