Skip to content Skip to sidebar Skip to footer

How To Open/close Sqlite Db In Android Properly

I have an app that functions properly and does not force close or crash. But when I look at LogCat, it occasionally gives me this: 05-20 15:24:55.338: E/SQLiteDatabase(12707): clo

Solution 1:

If you're using an instance of a DatabaseHelper class, and after you initialize the DBHelper object, every time you do work in the database you should call the open method before you do work, then create a new cursor, query the database, do work with the information you just stored in the cursor, when you're done close the cursor, then close the database. For example if you wanted to grab every item in a database you would do something like :

...    
DataBaseHelperdb=newDataBaseHelper(this);
... 
db.open();
Cursorcursor= db.getAllItems(); 
maxCount = cursor.getCount(); 
Randomgen=newRandom();
row = gen.nextInt(maxCount); // Generate random between 0 and maxif (cursor.moveToPosition(row)) {
    StringmyString= cursor.getString(1);  //here I want the second column
    displayString(myString); //private method
}
cursor.close();
db.close(); 

getAllItems is a public method in my DatabaseHelper, it looks like this in case you were wondering

publicCursorgetAllItems() {
    return db.query(DATABASE_TABLE, 
        newString[] {
            KEY_ROWID, 
            KEY_NAME
        }, 
        null, 
        null, 
        null, 
        null, 
        null);
}

This is how I access my database and I haven't gotten any of the errors you've got, and it works perfectly.

Solution 2:

I used to do the way @Shikima mentioned above but in complex applications which has many background services, multi-threading,etc it can get real tiresome when you have to manage many database instances and on top of that, opening and closing them.

To overcome this, I used the following method and it seems to be working fine.

1.

Declare and initialize an instance of YourDBHelperClass in your Application base class like this :

publicclassAppextendsApplication {
  publicstatic YourDBHelperClass db;

  @OverridepublicvoidonCreate() {
    super.onCreate();
    db = newYourDBHelperClass(getApplicationContext());
    db.open();

  }
}

2.

In you activity, or any other place you want to use the DB, initialize the YourDBHelperClass object like this :

YourDBHelperClassdb= App.db;

And then you can use the database anyway you want without having to worry about opening and closing it manually each time. The SQLiteOpenHelper takes care of the closing when the Application is destroyed

Solution 3:

You are probably not handling your database correctly; you are opening more database instances than you are closing.

There are a number of design patterns you can follow to correct this behavior. You might want to consult this answer for more information.

Post a Comment for "How To Open/close Sqlite Db In Android Properly"