【问题标题】:Filling ListView with AsyncTask (doInBackground() returning cursor)用 AsyncTask 填充 ListView(doInBackground() 返回光标)
【发布时间】:2012-06-05 02:17:30
【问题描述】:

我正在尝试使用 AsyncTask 填充我的 ListView。在评论中包含问题

private class DownloadDataTask extends AsyncTask<String, Void, Cursor> {
    private final ProgressDialog dialog = new ProgressDialog(ctx);


    @Override
    protected void onPreExecute() {
        this.dialog.setMessage(ctx.getString(R.string.AcquiringData));
        this.dialog.show();
    }


    @Override
    protected Cursor doInBackground(final String... args) {         

        DbAdapter dbAdapter = new DbAdapter(ctx);
        dbAdapter.open();
        // normally when I call this method from main class it reurns cursor full of values
        Cursor cursor = dbAdapter.fetchAllItemsInExpenses();

        return cursor;
    }


    protected void onPostExecute(final Cursor cursor) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
           //cursor is empty

    }

ctx 是在主类 OnCreate() 上设置的 Context

以下请求粘贴 fetchAllItemsInExpenses() 方法:

public Cursor fetchAllItemsInExpenses() {
    String query = "SELECT ... " //(some terribly boring and long query string, but trust me, it works perfectly fine)
    return SQLDb.rawQuery(query, null);
}

【问题讨论】:

  • 使用if(null!=cursor){cursor.getCount()}检查并检查您的方法fetchAllItemsInExpenses是否正确
  • 你能显示fetAllItemsInExpenses()的来源吗?另外,您之前是否考虑过使用CursorLoader
  • fetchAllItemsInExpenses() 当我从 Activity 类调用它时工作正常。但是需要一些时间,所以我决定将列表填充移至 AsyncTask。但是提供了代码。 @JasonRobinson 纠正我如果我错了,光标加载器是一种为加载光标而设计的任务?
  • @JacekKwiecień 因此得名:)
  • 就像你说的,它在支持包中一直可用到 API 4

标签: android android-asynctask android-cursor


【解决方案1】:

AsyncTask中试试这个...

private class DownloadDataTask extends AsyncTask<String, Void, Cursor> {
    private final ProgressDialog dialog = new ProgressDialog(ctx);
    Context ctx = null; //Add this and the constructor below

    public DownloadDataTask(Context context) {
        ctx = context;
    }

    ...

}

然后在您的Activity 中创建并执行AsyncTask,如下所示...

DownloadDataTask ddt = new DownloadDataTask(this);
ddt.execute(theArgs);

【讨论】:

  • 这有什么改变?我在活动的 OnCreate 上初始化的 ctx 变量拥有相同的东西
  • 您说您的ctxActivity 的一部分-您不应该尝试从doInBackground 线程访问Activity(UI 线程)中的任何内容。将其传递给构造函数允许doInBackground 访问AsyncTask ctx
  • 有道理...我会在该死的 x10 靴子再次启动时尝试一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多