Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database open/close - database not open

In every Activity, I have added in the onCreate() Method the following lines:

database = new DatabaseHelper(this);  
database.open();

And in every onDestroy() Method the following line:

database.close();

So as long as the activity is not destroyed the database is opened.

Sometimes some users get a force close if my app wants to update something in the database.

Following error:
java.lang.IllegalStateException: database not open
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1776)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1731)

How can this happen?
If I open the database in onCreate() and close it in onDestroy() Should it be always opened?!

like image 274
chrisonline Avatar asked Dec 10 '25 13:12

chrisonline


1 Answers

Binnyb is right, most likely your database is closed in background activity onDestroy while the error raises in the active activity. You have to open/close database just at the time you need to save/retrieve the data.

UPD:

Look at the google's dev docs, getWritableDatabase returns a cached object if a db was opened already.

like image 184
Konstantin Burov Avatar answered Dec 12 '25 04:12

Konstantin Burov