android - 在 Android 应用程序中保留数据库引用的 "best practice"方法是什么?

标签 android sqlite

我的大部分应用程序(由多个 Activity 和多个 fragment 组成)都使用通用数据库。我想这是非常标准的,所以我要问一个更笼统的问题。跟踪该数据库的“最佳”方式(以及原因)是什么?

我计划在帮助程序类中使用静态变量(因为我对 Activity 生命周期的有限理解意味着主要 Activity 可能会在稍后被破坏,所以离开它不是一个安全的地方)。但另一种选择是在每次需要时简单地使用 AsyncTask 来获取数据库引用“新鲜”(这是我第一次这样做的方式)。我不认为我可以使用额外的方式发送它,而且我不知道有什么技巧可以让它序列化。

我还缺少其他选项吗?我看过有关使用应用程序的引用资料,但我不熟悉这些内容。

最佳答案

I was planning on using a static variable in a helper class

这两种典型的方法,或者围绕数据库的 ContentProvider 包装器。

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

此外,由于您有多个 Activity ,让数据库由一个 Activity 持有并不是特别有用,因为其他 Activity 无法访问它。

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

这不是个好主意。您需要 SQLiteDatabase 的单个实例才能使内置线程同步工作。

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?

如前所述,有些人会使用 ContentProvider 作为数据库的包装器。这在尝试将此数据公开给第三方时非常有用。对于纯粹的内部使用,它有利有弊。

I've seen references to using an Application, but I'm not familiar with those.

因为自定义 Application 子类不会比拥有单例实例(静态数据成员)给您带来任何好处,所以我不担心。

关于android - 在 Android 应用程序中保留数据库引用的 "best practice"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110170/

相关文章:

android - 如何通过蓝牙传输套接字文件描述符的内容?

android - 如何在android中使用ffmpeg文件从URI播放音频文件

sqlite - 更新 sqlite 数据库中的记录时出现 MethodAccessException

node.js - sqlite3 macOS 塞拉利昂

sqlite - Flutter - 从数据库中获取记录并显示在 ListView Builder 中

c++ - SQLite Visual Studio 链接器错误

android - 无法将 crashlytics 与 ADT 集成到 Eclipse 中

java - UI 线程与其他线程之间的通信使用处理程序

Android:数组项上的监听器

php - 找不到 PDO 驱动程序(PhpStorm 和 SQLite)