Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
GVillani82 Avatar asked Apr 07 '26 16:04

GVillani82


1 Answers

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

like image 186
matreshkin Avatar answered Apr 10 '26 04:04

matreshkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!