【问题标题】:Updating ListView Adapter from AsyncTask从 AsyncTask 更新 ListView 适配器
【发布时间】:2013-08-28 14:51:02
【问题描述】:

我所拥有的是一个AsyncTask,,它在ListView 到达屏幕底部项目时立即启动,并在AsyncTask 中将新项目添加到ListView.

代码如下:

    @Override
    protected void onPostExecute(final List<ItemDailyRecord> records) {
        super.onPostExecute(records);
        ((ActivityHome)context).runOnUiThread(new Runnable() {
            public void run() {

                for (ItemDailyRecord p : records) {
                    adapter.add(p);
                }

                adapter.notifyDataSetChanged();
            }
        });

    }

 @Override
    protected List<ItemDailyRecord> doInBackground(Void... voids) {

        DbAdapterDailyRecord db = new DbAdapterDailyRecord(context);
        List<ItemDailyRecord> list = db.getRecordsFromTo(offset, count);

        return list;
    }

这是一个来自 ListView Adapter 的方法:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(position == getCount() - 1 && hasMoreItems){
            HistoryLoaderTask t = new HistoryLoaderTask(position + 1, pageSize, getContext(),this);
            t.execute();
            footer.setText("Loading . . .");
        }

错误信息是(如果我滚动列表视图太快:)

原因:android.view.ViewRootImpl$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触及其 意见。

任何想法如何解决这个问题?

【问题讨论】:

  • onPostExecute() 已经在 UI 线程中运行。 runOnUiThread() 调用没用。
  • 在doInBackground中显示你正在使用的代码
  • 但如果我删除它,也会出现错误消息:(
  • 另外,您不应该将该项目添加到引用该适配器而不是适配器本身的列表中吗?
  • 我用“doInBackground”方法更新了我的帖子。

标签: android multithreading listview adapter


【解决方案1】:

onPostExecute() 方法在 UI 线程上执行,因此您应该直接在此方法中更新 UI;无需生成新的 Runnable 对象。

【讨论】:

  • 但即使我直接更新UI,我也会遇到:只有创建视图层次结构的原始线程才能触摸它的视图。
  • 你的ListView适配器是什么类型的?
  • 公共类 AdapterHistoryList 扩展 ArrayAdapter
  • 可能与我正在使用的 Fragments 有关,因此在 UI 线程上没有正确调用。因为在我的代码中我有一个活动“ActivityHome”,并且在那里我动态加载了一个片段“MyFragment 扩展 SherlockFragment”。在这个“MyFragment”中,我有列表视图、适配器等......
  • 对我来说这不是问题的根源。如果您在调试器中运行它,并在getView()onPostExecute() 内设置断点,您应该能够看到哪个线程正在执行这些方法。它应该是 UI 线程,它将在 Eclipse 调试窗口中标记为 &lt;main&gt;。如果不是,看看你是否可以追踪(可能通过堆栈跟踪)是什么产生了这个另一个线程。
【解决方案2】:

您不应从适配器的 getView 执行异步任务。相反,您应该尝试使用 ListView 的 getLastVisiblePosition() 从列表所在的活动/片段中执行此操作

像这样--->

if(list.getLastVisiblePosition() == (dataSet.size() - 1)) {
// last item displayed
.... change the text off footer and execute async task
}

并在异步任务中将额外数据附加到数据集,然后在适配器上调用 notifyDataSetChanged()。

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多