I am new to Android development (to development overall to be frank), and as such I have been reading Commonsware Busy Coder's guide. While reading through the SQLite section, there are a couple things that are not %100 clear to me. Below is what I believe is going on as well as some questions. Please correct me if I am wrong in my thought process.
The author suggests that if you are going to use a database from more than just one Activity in your application, you shouldn't use the Context reference from each Activity to instantiate the SQLiteOpenHelper. Instead, you should use getApplicationContext()
provided by Activity.
By doing so, he uses the fact that getApplicationContext()
retrieves the singleton instance of Context created soon after the application process begins. Here is where my question arises. I think that if I were to use the Context provided by the Activity(this keyword) when instantiating SQLiteOpenHelper, each Activity will create its own instance of SQLiteOpenHelper. It appears to me that just using the Activity's Context does not inform the Application Context that there already is an instance of the SQLiteHelper created, and hence, it creates a new one instead of re-using the existing one. Is my thinking correct?
I think of Context (and correct me if I am wrong) as the developer's "gateway" to get information and resources provided by the Android OS (i.e. getting hold of a system service via getSystemService()
). But doing so using this (from an Activity) or using getApplicationContext()
has different implications. Using this, will get an instance of Context which is "local" to your current Activity, but using getApplicationContext()
references the whole application. If this is correct, does it mean that when I pass a reference to getApplicationContext()
to the SQLiteOpenHelper's constructor it will let my whole Application know that there is an instance of my SQLiteOpenHelper already created. How does SQLiteOpenHelper let the Application know about this? does it use some static method like public/private static dbCreated(Context context){//let context know there is an instance of this running} to let the Application know?
I am sorry if this is confusing.
Thanks ahead of time