Aut*_*M8R 14 sql multithreading android loader android-asynctask
我目前使用Loaders从我的ContentProvider中获取数据(以启用我的游标的自动更新).这种方法对于查询数据库是直截了当的,但它似乎不适合任何其他数据库操作(例如插入,更新,删除).
我的问题是:
小智 5
我在UI线程上完成了SQLite操作.我想这个问题真的变成了你的查询是否会花费很长时间.我的应用程序崩溃从来没有花太长时间在我的SQLite数据库上执行SQL调用.
话虽如此,如果您计划编写可能需要时间加载的复杂查询,您可能希望将其作为AsyncTask或Thread运行,并在需要时使用回调来更新UI.
这是关于Android上SQLite的一个很棒的教程(它还解决了你所讨论的一些复杂的sql时序问题):http: //www.vogella.com/tutorials/AndroidSQLite/article.html
所有 SQLite 操作不需要但应该在后台进行。即使是简单的行更新也会影响 UI 线程,从而影响应用程序的响应能力。
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)
更多细节:
| 归档时间: |
|
| 查看次数: |
11107 次 |
| 最近记录: |