GVillani82
GVillani82

Reputation: 17429

Android: opening and closing SQLite database

I'm developing and android application in which I often use access the local database. This database can be accessed from differents therads, so I have a coordination problem for the database. I use the following open() and close() method.

public void open(){ 
    mDb=mDbHelper.getWritableDatabase();
}

public void close(){
        mDb.close();
}

So, usually, when I need to access the db for some operations I open the database, then I perform some operation, and finally I close the database. The code I typically use for this purpose is the following:

    try {
        dbManager.open();
                    // database operation
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            dbManager.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

But, if for this piece of code is used from differnts threads (supposing thread A and thread B) the following situation may occurs:

A thread: performs open()
B thread: perfroms open()
A thread: perfroms some operation
A thread: performs close()
B thread: try to perform some operation but it fails!

So, the only solution I can guess I to perform open() when my application starts and close() when my application is stopped. I'm not sure that this can be this a good solution?

In effect, the documentation of getWritableDatabase() method (called from my open()) says:

Make sure to call close() when you no longer need the database

So, anyone can suggest me an alternative solution?

Upvotes: 3

Views: 2179

Answers (2)

matreshkin
matreshkin

Reputation: 2208

You can use the singletone instance and gennerally you can do not close database (but keep transaction closed). There is some information:

Android SQLite DB When to Close

Upvotes: 2

Buda Gavril
Buda Gavril

Reputation: 21647

Create a wrapper class, add an atomic integer member and every time you open the database, increment the member, when you close it, decrement the member and if the member is zero, actually close the db.

Upvotes: 1

Related Questions