【问题标题】:Android: Loading a listview from a database after populating it asynchronouslyAndroid:异步填充后从数据库加载列表视图
【发布时间】:2012-05-02 09:27:37
【问题描述】:

我正在尝试在从 Web 加载信息时显示进度对话框,该信息填充了创建 Listview 的 sqlite 数据库。我创建了一个异步类,它在下载信息时显示进度对话框,但之后列表视图为空。这可能是因为列表视图在异步之前已经加载。那么如何重新加载列表视图或以正确的方式执行此操作?到目前为止,这是我所拥有的(由于显示时间太长而忽略了后台处理):

private class DownloadInfo extends AsyncTask <Void, Void, Void>{
    //////////////////Open Dialog before execution ///////////
private ProgressDialog dialog;
    protected void onPreExecute(){
        dialog = new ProgressDialog(CandidatesList.this);
        dialog.setMessage("Loading Candidates from Webserver");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }
    ///////////////Background Processing//////////////////
    @Override
    protected Void doInBackground(Void... dbArray) {
    ////Load information from webserver and put it in sqlite///
        return null;

    }

    ///////After the processing is done //////////////
    protected void onPostExecute(Void unused) {
        dialog.dismiss();
    }

}

而on create如下:

DownloadInfo task = new DownloadInfo();
    task.execute();
Cursor c = db.getAllCandidates();
    candidates = new String[c.getCount()];
    if (c.moveToFirst()) {
        int i = 0;
        do {
            candidates[i] = c.getString(1);// insert Name into candidate
                                            // Array
            i++;
        } while (c.moveToNext());
    }
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
            candidates));

请帮忙, 谢谢

【问题讨论】:

    标签: java android listview asynchronous


    【解决方案1】:

    如果您想将数据库中的游标信息自动加载到 ListView 中,请为 ListView 使用SimpleCursorAdapter。 (您可能需要在异步完成后调用 notifyDataSetChanged()。)

    【讨论】:

    • 在 postExecute 中调用 notifyDataSetChanged()?在什么方面?
    • notifyDataSetChanged() 是 SimpleCursorAdapter 的继承方法。一种解决方案是将您的 AsyncTask 传递给您的适配器,是的,在 postExecute() 中调用 notifyDataSetChanged()。
    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多