[英]android - Updating ListView from AsyncTask called from custom adapter class
[英]Updating ListView Adapter from AsyncTask
我所拥有的是一个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线程上执行的,因此您应该直接在此方法中更新UI。 无需生成新的Runnable
对象。
您不应该从适配器的getView执行异步任务。 相反,您应该尝试使用ListView的getLastVisiblePosition()从列表所在的活动/片段中进行操作
像这样--->
if(list.getLastVisiblePosition() == (dataSet.size() - 1)) {
// last item displayed
.... change the text off footer and execute async task
}
然后在异步任务中将额外的数据追加到数据集,然后在适配器上调用notifyDataSetChanged()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.