简体   繁体   English

从AsyncTask更新ListView适配器

[英]Updating ListView Adapter from AsyncTask

what I have is an AsyncTask, that started as soon as ListView reached bottom item on a screen, and in AsyncTask it adds new items to the ListView. 我所拥有的是一个AsyncTask,它在ListView到达屏幕底部的项目后立即开始,并且在AsyncTask它将新项目添加到ListView.

Here is the code: 这是代码:

    @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;
    }

here is a method from ListView Adapter: 这是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 . . .");
        }

And the error message is(if I scroll the listview too fast :) 错误消息是(如果我滚动列表视图的速度太快:)

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 原因:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。

any ideas how to solve this issue? 任何想法如何解决这个问题?

The onPostExecute() method is executed on the UI thread, so you should be updating the UI directly in this method; onPostExecute()方法是在UI线程上执行的,因此您应该直接在此方法中更新UI。 no need to spawn a new Runnable object. 无需生成新的Runnable对象。

You shouldn't execute your async task from getView of your adapter. 您不应该从适配器的getView执行异步任务。 Instead you should try to do it from your activity/fragment where your list resides by using getLastVisiblePosition() of ListView 相反,您应该尝试使用ListView的getLastVisiblePosition()从列表所在的活动/片段中进行操作

Like this ---> 像这样--->

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

and in the async task append the extra data to dataset and then call notifyDataSetChanged() on the adapter. 然后在异步任务中将额外的数据追加到数据集,然后在适配器上调用notifyDataSetChanged()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM