Reputation: 1579
I'm using a common database for most of my app (which consists of multiple activities and multiple fragments). I imagine that this is pretty standard, so I'm asking a more general question. What is the "best" way (and why) to keep track of this database?
I was planning on using a static variable in a helper class (as from my limited understanding of the activity lifecycle means that the main activity can get nuked later, so that's not a safe place to leave it). But another option is to simply use an AsyncTask to get the database reference "fresh" every time I need it (which is how I'm doing it the first time). I don't think I can send it using extras and I don't know of any tricks to make it serializeable.
Are there any other options I'm missing? I've seen references to using an Application, but I'm not familiar with those.
Upvotes: 1
Views: 176
Reputation: 1006974
I was planning on using a static variable in a helper class
That, or a ContentProvider
wrapper around the database, are the two typical approaches.
as from my limited understanding of the activity lifecycle means that the main activity can get nuked later, so that's not a safe place to leave it
Moreover, since you have multiple activities, having the database be held by one activity is not especially useful, as the other activities cannot reach it.
But another option is to simply use an AsyncTask to get the database reference "fresh" every time I need it (which is how I'm doing it the first time).
That's not a good idea. You need a single instance of a SQLiteDatabase
for the built-in thread synchronization to work.
I don't think I can send it using extras and I don't know of any tricks to make it serializeable.
Agreed, that's not an option.
Are there any other options I'm missing?
As noted earlier, some people will use a ContentProvider
as a wrapper around the database. This is extremely useful when trying to expose this data to third parties. There are pros and cons on it for purely internal use.
I've seen references to using an Application, but I'm not familiar with those.
Since a custom Application
subclass will not gain you anything over having a singleton instance (static data member), I wouldn't worry about it.
Upvotes: 3