Trying to reopen an already closed object: SQLiteDatabase:

I am trying to delete something from the database and then insert a new value. I know little about databases, so I would be grateful for the advice on what is going on here.

I keep getting the following error:

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

Called from an async task, it works fine the first time, but the second time the task starts.

Here are some 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); } 
+6
source share
3 answers

Try it.

 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); } 
+12
source

It looks like you are creating an instance of SQLiteOpenHelper ( dbHelper ) dbHelper and getting a writable database ( sqlite ) from it, but then you close the database. If this is the last (or only) database link that is open, the entire database will be closed when you call sqlite.close() .

You can safely remove the sqlite.close() call in removeAndInsert() . When your AsyncTask done with the database, call dbHelper.close() to clear links to any links.

+8
source

try replacing sqlite.close(); on dbHelper.close();

+3
source

Source: https://habr.com/ru/post/954702/


All Articles