I have an activity that uses AsyncTask to download and save some data to the database. To open a database we need to pass Context param to the SQLiteOpenHelper’s onCreate method, which means that database somehow needs context.
And I’m just curious, what would happen when device turns and activity goes through destroy and create cycle? Is it ok to open database in activity’s constructor rather than in activity’s onCreate() method?
The problem is that I use DB from another thread and I want to know what exactly would happen when activity is being destroyed and recreated
One solution would be to use the ApplicationContext instead of the ActivityContext. You only need a static method that requests the ApplicationContext from the Application constructor.
If you use some kind of singleton to access the context, you won’t have any problems with concurrency.
See example here: http://androidcookbook.com/Recipe.seam?recipeId=1218
Another approach would be to use the LoaderManager which keeps track of your opened database connections.
See here: http://developer.android.com/reference/android/app/LoaderManager.html
(There is a complete example too)
The LoaderManager is available in the compatibility package for down to Android 1.5
Michael