Reputation: 4717
In my database helper class I have the open and close methods for the db.
public void open() throws SQLException
{
db = dbOpenHelper.getWritableDatabase();
}
public void close()
{
dbOpenHelper.close();
}
And also in my DbHelper class I have custom methods to insert deleted etc...
My question is, where should I open and close the Database ? Inside the custom methods od the helper or , before running each method inside the activity before and after, or, inside the onCreate() and onResume() ?
Upvotes: 0
Views: 60
Reputation: 9434
The best approach is to wrap the database in a ContentProvider. There are many advantages to doing this including disconnecting the database from the Activity life cycle events, and ensuring that all Activities see a common, up-to-date version of the data (for example if you do it right an activity holding a cursor that results from a query will be informed if some other activity changes the data accessible though the cursor.
However, if you feel this is too heavyweight an approach (it is a bit complicated), you can open/close in onCreate and onDestroy, but reissue any queries in onResume and commit any writes in onPause. Betware, however, that you will be operating on the UI thread, so queries, in particular, must be simple enough to operate within the time constraints of the UI thread.
Upvotes: 1