1

I was looking for a solution for making my slqite database, accessing syncronized and avoid problem with open/close connection, and I falled in this good answer:

In this solution, however, there is not a explicit closing of database. many argue that this is not a problem, but I would know how can I close the connection after the application is stopped.

note: In the aforementioned link the author of the answer suggest this:

With my implementation the singleton lives for the life of the application. Therefore I did not implement an explicit destructor, instead, in the app shutdown code (or crash handler) the database is explicitly closed. See Thread.setDefaultUncaughtExceptionHandler() which I used in ApplicationContext.onCreate() after I posted my sample code.

Can be this a good solution? If yes, how can I manage Thread.setDefaultUncaughtExceptionHandler() ?

EDIT:

I want also, that if the database resource is not available, the requiring thread will wait until the database is released. Can I use this code? the isDbLockedByOtherThreads() is deprecated

private myDatabase(){
        final DbHelper mDbHelper =new DbHelper(ApplicationFramework.getContext());   
        mDB = mDbHelper.getWritableDatabase();
        while(mDB.isDbLockedByCurrentThread() || mDB.isDbLockedByOtherThreads()) {
            //db is locked, keep looping
        }
    }
4

1 回答 1

2

You need not to worry about closing database connection after the application is stopped it automatically gets closed.

Actually there is only one connection internally, you make its different instance thats a different thing. Thats why many people says closing of database connection does'nt make any sense.

Always have a single static object of database connection it will be safe and less exception prone, and don't worry about closing it.

If you try to write to the database from actual distinct connections at the same time, one will deifnately get failed . It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.

Answer for updated query

Use only Single static instance of your db connection no need to make others threads, all operations will be automatically synchronised.

于 2013-05-02T09:42:42.877 回答