使用AsyncTask填充ListView(doInBackground()返回游标)

时间:2012-06-04 18:06:29

标签: android android-asynctask android-cursor

我正在尝试使用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);
}

1 个答案:

答案 0 :(得分:0)

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);