Android, when should I open and close db connections?

Overview. Opening db connections on onStart and async tasks has become quite complicated. Is it wrong to have globally accessible db connections? If it is bad, which is better?

Details: I have an application that connects to sqlite3 database in several steps. At first, there were not many places where I needed to access the database, so I just opened and closed every time I needed access. Then there were more places that needed access to it, since, as suggested in another question, I started to open database connections in the onStart method, which needed a connection and closed it in the onStop method.

This worked until I needed connections in some of the asynchronous tasks that survived the activity. Since the onStop method for this operation was called and the connections were closed, by the time the asynchronous task tried to access the database, it had failed. As a solution, I created separate connections for each async task that were opened in the onPreExecute method and closed in the onPostExecute method.

This led to a lot of opening and closing connections, and I wonder if making globally accessible db connections in the application context is a good idea. This will definitely clear a lot of code and remove all closed db exceptions that occur if I forget to close the connection or the application experiences force. Has anyone else tried this / seen any problems with this approach?

+5
source share
2 answers

I ran into similar issues a few weeks ago. I use several classes that have persistence in SQLite db.

Since I wanted to separate actions from persistence, I created static inner classes (called managers) for those who need perseverance. Each time I create an instance of the manager, a db connection is created, and after using the manager I explicitly close it. If I had global managers to access tables, they should be synchronized due to concurrency, and I don't know when I should close these db connections. So I did it like this.

Hope this helps!

+2
source

BaseAsyncTask, onPreExecute() onPostExecute() db.

AsyncTasks BaseAsyncTask super.onPreExecute() super.onPostExecute() doInBackground().

+2

All Articles