Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

java - Android: Accessing single database from multiple activities in application?

I have a todo list type application that stores all of the note data in a sqlite3 database. Each activity in the application needs access to the database to edit different parts of the data in real time.

Currently, I have each activity open its own DBManager object (the helper class I created to manage the database). This is causing problems though and I would like a slightly more global access solution so I don't have to keep opening/closing/creating a database.

I'm considering several options, and would like to hear pros and cons of each as well as other suggestions.

  1. Singleton style. Have a wrapper class that returns a reference to the only database manager so any activity that needs it can use it.

  2. Static Manager. Have the manager class be entirely static members and have it open the database on load. Easily accessible by anyone that needs it (which is everyone).

  3. Merger between 1 and 2. I could make a database manager class that initializes the member singleton instance of the database and all of the data manipulation methods were static. Then I wouldn't even need a reference to the singleton to access the database. I like this solution best, please point out downsides.

Suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my opinion, the Content Provider is complicated and if you are not sharing with activities that are not your own, you don't need it. Therefore, I suggest you use a singleton class first. Then if you have more time or need it, go for the Content Provider.

I've used a singleton successfully for 6 months without much difficulty. (I was careful to really make it a singleton though, only one instance that loads the data once)

Singleton

  • Advantage: Easy to implement
  • Advantage: because I used a common instance, I could implement caching easily and hence make the application not have to do to the database as often
  • Disadvantage:can't share your data with external Activities

Content Provider

  • Advantage: You can share your data with external Activities
  • Advantage: You can integrate with the Search API
  • Disadvantage: Complicated, need to represent your data in a different way
  • Disadvantage: Yet another Android API to spend time learning

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...