Android Create Database instance for the entire application or class - android

My app has several AsyncTaskRunners which are constantly access the database. I keep getting ThreadPool errors because of a closed database instance. Originally I had a new instance opened and then closed again, each with a different name every time. So every method that accessed the database would open its very open instance do whatever and then close that instance.
I was hoping that it would have been more efficient to open a single instance and then not close it so that every method within the AsyncTask would just do its thin with the database.
Is there a way to open a database instance when the app starts and not close it, and then get & put throughout the entire application just be referencing that instance?
Or is there a way to open an instance for my AsyncTaskRunner class so that all methods in that class can talk to the database?
I have tried initializing a database instance at the beginning of the class with
SQLDatabase db;
and then later in the doInBackground() I would open an instance of db and not close it. Then the various methods would try to talk to the db but with no success.

Related

Re-create database when using Content Providers

My Android App has a SQLite Database and a Content Provider. This Content Provider is registered in the app's AndroidManifest.xml. It is not exported, so only my app can see it.
As part of resetting the user's profile, I want to completely wipe this database and re-create it from scratch. At first I tried calling deleteDatabase() from the activity's context. This works, but only if the app is closed and reopened afterward. Otherwise it will crash when I attempt to insert rows saying the database is read-only. My understanding is the connection needs to be closed first before calling deleteDatabase(). Yet, the connection is managed by the Content Provider and shouldn't be manually closed, as far as I understand.
As an alternative, I am using the call() method from the ContentResolver to call a custom function that will delete all of the data in the tables and reset the sequence counts manually.
This works, but now I have to delete the data from each table manually and will have to keep track of any changes I make in the future.
Is there a better way to delete the entire database and have the onCreate() of my DatabaseHelper (SQLiteOpenHelper) trigger when using a ContentProvider?
One suggestion that comes to mind is to have your custom function drop the tables and recreate them. You already have the code to create the tables in onCreate() of DatabaseHelper. Refactor this somewhere that is accessible by both DatabaseHelper and the custom method.

Clarifying When to Open and Close a DataSource

Ive done a lot of Googlig on this topic and I'm confused as to best practice.
Initially I had:
A) Created a DataBase object in my main class header area and then just passed it to functions as needed. I then later read that a DataBase should be opened and closed each time before use.
so then I:
B) went to each function (passing Context) which uses a SQL command and created a new DataBase object, created a filled cursor via SQL, and then closed the Database before returning. However, I then later read that it's expensive to do this.
now i'm thinking that:
C) I should create a new Database object in each subclass that uses one, and open and close it as needed.
Im sorry for the noob and seemingly design question (delete it if it's out of scope of StackOverflow), however, I truly am confused of how this should be handled to avoid errors, and how Google wants us to do it.
Regards
The Android docs recommend using an SQLiteOpenHelper, which caches the database object. From the SQLiteOpenHelper reference:
Once opened successfully, the database is cached, so you can call this
method every time you need to write to the database. (Make sure to
call close() when you no longer need the database.)
So, I'd go for a singleton carrying an instance of SQLiteOpenHelper, so you can access it from anywhere. Then get the database where you need it, and close it on exit points of your application (if any). That way you only open a database if required, but can re-use the same connection for other tasks as well.
If you do only need the database for single tasks and/or there are other Applications accessing the same database, you may consider closing it directly after your database-tasks are done; there is a discussion about closing in another question.

What would happen if I don't close the database in Android?

This title may sound a little bit crazy, but this is what is making me confused. My app heavily uses local database operations. As suggested in the Android docs and some blogs, I extended the SQLiteOpenHelper class and defined all my DB operations there. As some of my DB operations execute in threads, opening and closing of the db causes some IllegalStateExceptions. So, I made my DB helper as Singleton and it resolved those issues, also getting rid of the open and close operations for every DB action. Now everything seems to be working fine even though I never close the DB.
My confusion is that is it necessary to close DB?
If so, what is the right place to do so, is it in onDestroy of the main activity or somewhere else?
If I don't close DB, what are the side effects?
You can catch IllegalStateException if you'll try to open again the same database.
If you create instance of DBHelper in onCreate method of main activity - it would be write to close db in onDestroy. So, you can be sure, that next time in onCreate your database is not opened already.
If you have reference to DBHelper in service, than it should be opened and closed in service, and not in activity.
You can also use Application class for opening db, but than it will opened every time when you app starts (for example when you receive BroadcastReceiver)
The reason why you get exceptions is that you are trying to write/read from the same database via different threads.
I believe the best place to close your database would be inside the onDestroy() of your mainActivity.
I faced same problem.I opened database ,perform some operation and i forget to close.Actually i saw some exceptions i logcat that is "Leak found" db is opened and never closed.

How and when close sqlite database in application with lot of activities and services

I read lot of about this topic but no solution can be used in my application.
Suppose there are few services and lot of activities that need to access db.
Of course only one activity is active. But in the worst scenario there is one activity and two services running background accessing db.
So when I close db from activity's onResume - service accessing db would throw exception.
And same is when I close db from service's onDestroy and there is opened cursor in activity.
I hold some kind of DBManager in my application object as singleton. I init DBManager in Application.onCreate. But there is no place to close db without risking that another Service and activity is accesing this.
So now I never close DB - are there any consequencies doing that?
Is there same simple(or not too complicated) solution to close DB?
here are my applications in market
russian version
english version
You should try using ContentProviders, the Android system will then handle creating/opening/closing the database as it needs to.
I do the same, I use a singleton database object and never close it until my application is destroyed. I didn't notice any issues so far. A more detailed answer is here:
https://stackoverflow.com/a/4842251/448625

Android SQLite connection management

I'm working with SQLite in my android project. There is a feature that is clear to me -- if there are multiple threads working with DB then they should use only ONE instance of DBHelper and SQLite guarantee a safe access (even if it is concurrent) to the DB.
But I still have one thing needed to be clarified. How should I manage with DB connection (SQLiteDatabase object)? How often should I call geWritableDatabase() and close()? Is it ok if I call these methods once? Or it's better to obtain SQLDatabase object and close one every time I perform read/write operation on DB?
It is handled by default... I mean if a writtable database open, whenever you try to access read-only database it closes writtable one and create new read-only database instance. As far as i know :)

Categories

Resources