Android: opening and closing SQLite database

人盡茶涼 提交于 2019-12-22 09:56:34

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/16171512/android-opening-and-closing-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!