Hi I’m trying to clean up my code to remove errors stating that my db connection was opened but not closed correctly.
If I have a db.open() then a few try catch statements around db query’s then a db.close() following the try catch will it use the same db connection within the try catches or does java discretely run the try catch statements so the db connection is not available.
In short, should i have code something like this:
db.open();
try {
// here
db.getThings()
} catch () {
// there
}
try {
// here 2
db.getMoreThings()
} catch () {
// there 2
}
db.close();
Or this:
try {
// here
db.open();
db.getThings()
db.close();
} catch () {
// there
}
try {
// here 2
db.open();
db.getMoreThings()
db.close();
} catch () {
// there 2
}
I’d have thought the first solution of opening one db connection is the better one. But i’m running into issues with not closing db connections and i’m at the point of thinking there’s a fundamental issue with my design.
I’ve also tried opening the connection in onResume() then close in onPause() but still having problems.
There is a recommendation to close DB connection as soon as you selected data, so in my app I mainly use the following template:
it worked for me.