简体   繁体   中英

What is the “best practice” way to keep a database reference in an Android app?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM