Android:应用程序中的数据库是否应该以异步方式访问?

发布于 2024-12-11 23:46:25 字数 221 浏览 2 评论 0原文

我正在制作一个使用 SQLite 数据库来存储数据的应用程序。有时,在访问数据库的活动之间切换时,我的应用程序会冻结,特别是当正在启动的活动在 onCreate() 方法中访问数据库时。

我应该:

  • 使用异步任务或类似任务访问数据库
  • 使用某种管道来控制数据库请求?

如果需要的话,您能给我指出相关的代码示例吗?

提前致谢!

I'm making an app that uses a SQLite database to store data. Sometimes my app freezes when switching between activities that access the database, especially when the activity being started accesses the database in the onCreate() method.

Should I:

  • Access the database using an async task or similar
  • Use some kind of pipeline to control database requests?

Could you point me to relevant code samples if nessecary please?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幻梦 2024-12-18 23:46:25

是的,您必须使用异步访问,这是最佳实践。
SDK 包含专门用于此目的的AsynchTask。

BuyAsyncTask extends AsyncTask<Item, Void, Item> {
    @Override
    protected Item doInBackground(Item... params) {
        ..use DB here
    }

    @Override
    protected void onPreExecute() {
        ..some easy operation befor start thread
    }

    @Override
    protected void onPostExecute(Item resultTask) {
        ..do what you want, thread is finish
    }

}

Yes, yor must use asynch access, this is best practice.
SDK contains AsynchTask especially for this.

BuyAsyncTask extends AsyncTask<Item, Void, Item> {
    @Override
    protected Item doInBackground(Item... params) {
        ..use DB here
    }

    @Override
    protected void onPreExecute() {
        ..some easy operation befor start thread
    }

    @Override
    protected void onPostExecute(Item resultTask) {
        ..do what you want, thread is finish
    }

}
千纸鹤 2024-12-18 23:46:25

我有一个更好的解决方案:

我正在使用管道系统,其中我将可运行对象发布到管道中,并按照发布的顺序执行。我发现这个解决方案易于管理、简洁且高效。

管道的示例如下: http://mindtherobot .com/blog/159/android-guts-intro-to-loopers-and-handlers/

I have a better solution:

I am using a pipeline system, where I have runnables that are posted into the pipeline that get executed in the order they were posted. I find this solution easy to manage, neat and efficient.

An example of pipelining is here: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文