Android SQLite查询,插入,更新,删除,总是需要在后台线程?

Aut*_*M8R 14 sql multithreading android loader android-asynctask

我目前使用Loaders从我的ContentProvider中获取数据(以启用我的游标的自动更新).这种方法对于查询数据库是直截了当的,但它似乎不适合任何其他数据库操作(例如插入,更新,删除).

我的问题是:

  1. 是否所有SQLite操作都需要在后台线程上,或者在UI线程上执行插入,更新或删除单行等简单操作是否安全?
  2. 什么是一个很好的设计模式,以确保所有查询都通过后台线程?我想实现AsyncTask,我应该创建一个SuperTask,这样可以扩展AsyncTask并执行每个SQLite操作吗?(额外奖励:你能提供简单的例子吗?)

小智 5

我在UI线程上完成了SQLite操作.我想这个问题真的变成了你的查询是否会花费很长时间.我的应用程序崩溃从来没有花太长时间在我的SQLite数据库上执行SQL调用.

话虽如此,如果您计划编写可能需要时间加载的复杂查询,您可能希望将其作为AsyncTask或Thread运行,并在需要时使用回调来更新UI.

这是关于Android上SQLite的一个很棒的教程(它还解决了你所讨论的一些复杂的sql时序问题):http: //www.vogella.com/tutorials/AndroidSQLite/article.html


13r*_*ac1 5

  1. 所有 SQLite 操作不需要应该在后台进行。即使是简单的行更新也会影响 UI 线程,从而影响应用程序的响应能力。

  2. Android 包含AsyncQueryHandler抽象类:

    一个帮助器类,可帮助更轻松地处理异步 ContentResolver 查询。

以下是在 Android 中使用 AsyncQueryHandler 异步访问内容提供程序的两个示例实现。会员类:

class MyQueryHandler extends AsyncQueryHandler {

    public MyQueryHandler(ContentResolver cr) {
        super(cr);
    }

    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
        // query() completed
    }

    @Override
    protected void onInsertComplete(int token, Object cookie, Uri uri) {
        // insert() completed
    }

    @Override
    protected void onUpdateComplete(int token, Object cookie, int result) {
        // update() completed
    }

    @Override
    protected void onDeleteComplete(int token, Object cookie, int result) {
        // delete() completed
    }
}
Run Code Online (Sandbox Code Playgroud)

匿名类:

AsyncQueryHandler queryHandler = new AsyncQueryHandler(getContentResolver()) {
    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

        if (cursor == null) {
            // Some providers return null if an error occurs whereas others throw an exception
        }
        else if (cursor.getCount() < 1) {
            // No matches found
        }
        else {

            while (cursor.moveToNext()) {
                // Use cursor
            }

        }
    }
};
Run Code Online (Sandbox Code Playgroud)

更多细节:

  1. 实现 AsyncQueryHandler

  2. http://www.trustydroid.com/blog/2014/10/07/using-asyncqueryhandler-with-content-provider/