活动之间共享的Andr​​oid SQLite数据库 [英] Android SQLite database shared between activities

查看:110
本文介绍了活动之间共享的Andr​​oid SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是共享一个数据库SQLite的几项活动之间的最佳方法是什么?从数据库表中显示的ListView,并且还删除/插入记录将被执行。我听说不便有关服务,但并没有发现例如我的问题。现在,我已经打开DB SQLiteOpenHelper类。我将OnPause()关闭数据库,并在onResume打开它()。但我不能插入数据子活动,以分贝,水木清华出了问题。

What is the best way for sharing one SQLite DB between several activities? Tables from DB are shown in ListView, and also deleting/inserting records is to be performed. I heard smth about Services, but did not found example for my problem. Now I have SQLiteOpenHelper class for opening DB. I close db in OnPause() and open it in onResume(). But I can't insert data to db from sub-activity, smth goes wrong.

推荐答案

你的应用程序创建一个应用程序类。这将在内存中保持活跃,只要任何部分应用程序的运行。您可以从onCreate方法创建您的数据库,并清理了onTerminate方法。 (请注意,不能保证onTerminate将被调用,所以你应该小心你依靠在这里。但由于SQLite数据库只是一个文件,并agressively刷新,关闭操作是一种礼貌不是更必要的。)

Create an Application class for your app. This will remain active in memory for as long as any part of your App is running. You can create your DB from the onCreate method and clean it up in the onTerminate method. (Note that there is no guarantee that onTerminate will be called, so you should be careful about what you depend upon here. However, since a SQLite database is just a file, and is agressively flushed, the close operation is a courtesy more than a necessity.)

您可以通过从getApplication的任何活动访问应用程序,所以数据库总是会提供给你。

You can access the application from any Activity via "getApplication", so the DB will always be available to you.

有关详细信息,请参阅<一href="http://developer.android.com/guide/appendix/faq/framework.html#3">http://developer.android.com/guide/appendix/faq/framework.html#3.

For more info, see http://developer.android.com/guide/appendix/faq/framework.html#3.

更新:

根据要求,这是一个使用getApplication的一个例子。这真是令人难以置信的简单。

As requested, here's an example of using getApplication. It's really incredibly simple.

  SQLiteDatabase mDB;
  @Override protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDB = ((MyApplication)getApplication()).mDB;
  }

如果每一个活动包括该code,那么每一个活动都会有它自己的MDB字段,引用相同的底层共享数据库对象。

If every activity includes this code, then every activity will have its own mDB field which references the same underlying shared DB object.

这篇关于活动之间共享的Andr​​oid SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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