安卓:从多个活动的应用程序访问单一的数据库?多个、应用程序、数据库

2023-09-04 06:49:52 作者:宝宝少女心

我有一个存储在一个sqlite3的数据库中的所有音符数据的待办事项列表类型的应用程序。在应用程序的每个活动需要访问数据库实时编辑数据的不同部分。

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.

目前,我有每个活动开了自己的DBManager对象(我创建管理数据库的辅助类)。这虽然造成的问题,我想稍微全球接入解决方案,所以我不必保持打开/关闭/创建数据库。

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.

辛格尔顿风格。有一个返回引用唯一的数据库管理器,以便任何需要它可以使用它的活动包装类。

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

静态管理。有经理类是完全静态的成员,并把它打开数据库的负载。任何人都需要它(这是每个人)很方便。

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).

合并1和2之间我能有这样的初始化数据库和所有的数据处理方法的成员单实例的数据库管理器类是静态的。然后,我甚至不会需要一个参考单来访问数据库。我喜欢这个解决方案最好的,请大家指出不足之处。

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.

建议?

推荐答案

在我看来,内容提供商是复杂的,如果你不与那些不是你自己的活动分享,你不需要它。因此,我建议你先用一个单独的类。然后,如果你有更多的时间还是需要它,去为内容提供商。

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.

我已经使用了单成功的6个月没有太大的困难。 (我很小心,要真正使之成为单身,虽然,只有一个实例加载一次数据)

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)

辛格尔顿

优点:易于实施 的优势:因为我用一个共同的 例如,我可以实现缓存 很容易,因此使应用程序 没有尽到数据库 常 缺点:不能与外部活动共享您的数据 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

内容提供商

的优势:你可以分享你的数据 与外部活动 的优势:你可以用集成 搜索API 缺点:复杂,需要 在不同的重present数据 方法 缺点:然而,另一个Android的API 花时间学习 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