最佳实践:管理fragment之间的android数据库引用
如何处理显示数据列表的片段和在后台更新数据的不同线程/类之间的引用。因此,我需要能够通过 Observer-inf 或类似的东西从片段外部强制更新。
目前,我正在使用虚拟工厂类根据我的默认设置创建一个新的 SqlLiteDatabase 对象。
public static SQLiteDatabase initFor(Context context) {
db = context.openOrCreateDatabase(NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
return db; }
然后我从每个片段调用它并设置适配器,这同样适用于数据插入器线程。要关闭数据库,我重写活动的 onDestroy() 并调用: initFor(this).close(); 。
这非常难看,并且在方向改变时失败。我正在考虑 SQLiteOpenHelper,但我不知道它对我有什么帮助。
How do I handle references between Fragments showing list of data and different threads/classes updating data in the background. Because of this I need to be able to force update from outside of the Fragments via Observer-inf or something similar.
Currently I'm using dummy factory-class to create a new SqlLiteDatabase object, based on my default settings for it.
public static SQLiteDatabase initFor(Context context) {
db = context.openOrCreateDatabase(NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
return db; }
Then I call this from each fragment and sets up adapters, the same applies to the data-inserter-threads. To close the db, I override my activity's onDestroy() and call: initFor(this).close(); .
This is very ugly and it fails on orientation change. I'm thinking of SQLiteOpenHelper but I don't know how it will help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在另一个线程(在服务中)访问数据库,然后与一个类(可能是您的帮助器)进行对话,然后通过在扩展应用程序的类中初始化的单例来访问该帮助器类。您可以通过调用从任何片段中获取应用程序类
You should access your database on another thread (in a Service) then have this talk to one class (which could be your helper), you then access this helper class through a singleton initialized in a class that extends Application. You can get your Application class from any of your fragments by calling