views:

106

answers:

3

... that's the question.

In last days I'v got very often many error messages because of database leak in my application, so now I open Database, get query results from it and close DB again.

But I use also a cursoradapter for my autocompletetextview.

Should I also do it on that way there: open DB, get cursor, close DB?!

I mean, I haven't got any problems because of not doing that, but ...

So I need tips from experts, tips from you

Thank you,

Mur

A: 

You should always close your DB connection.

Tyler
I just thought, if that makes sense to reopen DB everytime the user types new character in autocompletetextview. Maybe there are other solutions?!
Mur Votema
Well, opening a DB connection is pretty expensive, so it depends on the context of the application. The most ideal option would be to opening the connection to the DB as late as possible, leaving it open until the last query has been called, and then finally closing it.
Tyler
In my case it would be the time the user is ready with typing and click an entry from suggestionlist or a button. but how should cursoradapter notice that. I don't see any method to destroy or close cursoradapter ... but i have now an idea. i implemented custom cursor adapter, so I can write a close method ... thanks :)
Mur Votema
... or I just close DB-Connection in a finalize-method?! Hmmm .. it's a good idea as well .. or not?
Mur Votema
A: 

do not consider using finalize() to close a DB connection. there's no guarantee when it will be called, or even if will ever be called. for more details, see "Effective Java" second edition item 7.

can you utilize onPause(), onResume() to close / open the connection? i believe android provides some guarantee that those are called.

farble1670
+1  A: 

You should be able to open your database in the onCreate method and close it in the onDestroy method. This will guarantee that it will be available for as long as the activity is "alive" and that it will be cleaned up eventually.

Further, you should probably use "startManagingCursor" on the cursor that you use with your adapter. This will make sure that it is deactivated, requeried, and closed as necessary on pause, resume, and destroy respectively. Cursors that aren't used in adapters should be closed as soon as you are finished getting data from them.

There should be no leaks if you follow these rules.

beekeeper
I don't understand people from google. They give some tutorials for using database or cursors (eg, notepad tutorial). I've never seen there any close-methode either for cursors or for database ... I also tried startManagingCursor, but I've got problems with that ... can't remember why
Mur Votema
Well, the lack of close cursors is probably because everything they are doing is covered by startManagingCursor, which they aggressively promote. Failing to close the DB in onDestroy is certainly sloppy, but I don't know how dangerous it is.
beekeeper