在 Android 应用程序中让所有活动共享一个 SQLiteOpenHelper 实例是否可以? [英] Is it OK to have one instance of SQLiteOpenHelper shared by all Activities in an Android application?

查看:22
本文介绍了在 Android 应用程序中让所有活动共享一个 SQLiteOpenHelper 实例是否可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 SQLiteOpenHelper 的单个实例作为子类应用程序的成员,并让所有需要 SQLiteDatabase 实例的活动从一个助手中获取它?

Would it be OK to have a single instance of SQLiteOpenHelper as a member of a subclassed Application, and have all Activities that need an instance of SQLiteDatabase get it from the one helper?

推荐答案

拥有单个 SQLiteOpenHelper 实例有助于处理线程情况.由于所有线程将共享公共SQLiteDatabase,因此提供了操作同步.

Having a single SQLiteOpenHelper instance can help in threading cases. Since all threads would share the common SQLiteDatabase, synchronization of operations is provided.

但是,我不会创建 Application 的子类.只需有一个静态数据成员,即您的 SQLiteOpenHelper.这两种方法都为您提供了可以从任何地方访问的东西.但是,Application只有一个子类,这让你更难使用Applicationother子类(例如,GreenDroid 需要一个 IIRC).使用静态数据成员可以避免这种情况.但是,在实例化此静态 SQLiteOpenHelper(构造函数参数)时,请务必使用 Application Context,以免泄漏其他一些 Context.

However, I wouldn't make a subclass of Application. Just have a static data member that is your SQLiteOpenHelper. Both approaches give you something accessible from anywhere. However, there is only one subclass of Application, making it more difficult for you to use other subclasses of Application (e.g., GreenDroid requires one IIRC). Using a static data member avoids that. However, do use the Application Context when instantiating this static SQLiteOpenHelper (constructor parameter), so you do not leak some other Context.

而且,在您不处理多个线程的情况下,您可以通过为每个组件使用一个 SQLiteOpenHelper 实例来避免任何可能的内存泄漏问题.但是,在实践中,您应该处理多个线程(例如,Loader),因此此建议仅适用于琐碎的应用程序,例如某些书籍中的应用程序... :-)

And, in cases where you aren't dealing with multiple threads, you can avoid any possible memory leak issues by just using one SQLiteOpenHelper instance per component. However, in practice, you should be dealing with multiple threads (e.g., a Loader), so this recommendation is only relevant for trivial applications, such as those found in some books... :-)

这篇关于在 Android 应用程序中让所有活动共享一个 SQLiteOpenHelper 实例是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆