Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attempt to re-open an already-closed object: SQLiteDatabase:

Tags:

android

sqlite

I'm trying to delete something from a database then insert a new value. I don't know much about databases, so would appreciate advice on whats going wrong here.

I keep getting the following error:

Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:

Its called from an async task, works fine the first time, but breaks the second time that the task is triggered.

Here are the important snippets:

 public void removeAndInsert(String configRaw) {
    SQLiteDatabase sqlite = null;
    try {
        sqlite = dbHelper.getWritableDatabase();
        removeAndInsert(configRaw, sqlite);
    .....
    finally {
        if (sqlite != null) {
            sqlite.close();
        }
    }



void removeAndInsert(String configRaw, SQLiteDatabase sqlite) throws SQLException {
    ContentValues initialValues = new ContentValues();
    initialValues.put(DBOpenHelper.CONFIG_CACHE_RAW_DATA, configRaw);
    sqlite.delete(DBOpenHelper.CONFIG_CACHE_TABLE_NAME, null, null);
    sqlite.insert(DBOpenHelper.CONFIG_CACHE_TABLE_NAME, null, initialValues);
}
like image 537
serenskye Avatar asked Sep 26 '13 17:09

serenskye


1 Answers

Try this.

public void removeAndInsert(String configRaw) {
  SQLiteDatabase sqlite = null;
  try {
    sqlite = dbHelper.getWritableDatabase();
    synchronized(sqlite) {
      removeAndInsert(configRaw, sqlite);
    }
  .....
    finally {
    if (sqlite != null && sqlite.isOpen()) {
        sqlite.close();
    }
}

void removeAndInsert(String configRaw, SQLiteDatabase sqlite) throws SQLException {
  ContentValues initialValues = new ContentValues();
  initialValues.put(DBOpenHelper.CONFIG_CACHE_RAW_DATA, configRaw);
  sqlite.delete(DBOpenHelper.CONFIG_CACHE_TABLE_NAME, null, null);
  sqlite.insert(DBOpenHelper.CONFIG_CACHE_TABLE_NAME, null, initialValues);
}
like image 85
DroidT Avatar answered Oct 15 '22 13:10

DroidT