I am using a database that I need to access in all activities. So I created a class MyDBAdapter with all the methods open, create, getData etc…
To access the DB I see two different ways:
a. In each activity do I now write: MyDBAdapter db = new MyDBAdapter();
which means a new DBAdapter would be created in each activity. Each would open the same DB and have to close it. This also means that the same DB might be opened by several activities – is that OK? Or do I manually ensure that the DB is closed everytime I switch activities?
or
b. create only one instance of the DBAdapter in the first activity and pass it everytime to the next activity using putExtra("Task", x);
Then the DB gets only opened and closed once in the very first activity.
Which one is a better approach?
Thanks very much.
Generally you have to close the database, right after you finish working with it (manually call
db.close()). This mean that if you use your database in multiple activities, you have to close it every time after you have done using it. That said, it’s up to you if you will make callsMyDBAdapter db = new MyDBAdapter();in every activity or you will make a static reference to it. After all, if you have some local variableMyDBAdapter dbin some code block, it will be garbage collected at some point.Also generally speaking, you don’t want your database operations in your Activities, because this way they will be executed on the UI Thread, blocking it, until they finish their db operation. You might want to use AsyncTask for your db operations which will create a separate Thread for db operations (and handle it for you). Here’s a great tutorial on using AsyncTasks.