从适配器启动的AsyncTask更新TextView(getView)

时间:2013-10-30 11:31:01

标签: android multithreading android-asynctask textview adapter

我遇到一个奇怪的问题,从AsynTask更新TextView。 在我的适配器的getView函数中,我启动一个AsyncTask来计算一个数字并在屏幕上显示它。

问题是对于单个项目多次调用getView函数,因此计算的数字是我要显示的数字的几倍,效率不高。

我已经被调查并意识到每当我尝试限制os调用AsyncTask时,该数字不会显示在屏幕上(没有错误消息或例外)

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.category_item, null);
    TextView tvCategory = (TextView) rowView.findViewById(R.id.tvCategory);
    TextView tvUnreadNews = (TextView) rowView.findViewById(R.id.tvUnreadNews);

    Category cat = mCategoriesList.get(position);
    tvCategory.setText(cat.getName());
    if(!cat.isInitialized()) //<-- If I delete this line it works, but inefficienly, as the AsyncTask is launched many times repeatedly
    {
            cat.setIsInitialized(true)
        new GetNewsForCategoryTask(cat, tvUnreadNews, mContext).execute(cat.getId());
    }
    return rowView;
}

这是AsyncTask。重复调用时正确更新TextView,但在类别只调用一次时不更新值:

public class GetNewsForCategoryTask extends AsyncTask<String, Integer, JSONArray>{

private Context mContext;
private String mCategoryId;
private TextView mTvUnread;
private Category mCategory;

public GetNewsForCategoryTask(Category cat, TextView tvUnread, Context context) {
    mTvUnread = tvUnread;
    mCategory = cat;
    mContext = context;
}

@Override
protected JSONArray doInBackground(String... params) {
    mCategoryId = params[0];

     ...

}

@Override
protected void onProgressUpdate(Integer... values) {
    mTvUnread.setText(Integer.toString(values[0]));
}

@Override
protected void onPostExecute(JSONArray result) {
    if(result != null && mThrown == null)
    {
        publishProgress(mCategory.getUnreadNewsSet().size());
    }
}

}

有人可能是这种奇怪行为的原因吗?我检查了AsyncTask只在专业类别启动时正确调用,但只是不更新​​布局。为什么要推出几次专业类别的作品?

更新: 我一直在测试,看起来像getView()函数的问题。如果我检查变量是否已经初始化,那么只有ListView的第一个元素会改变...以及ListView中其他项的所有值!!

看起来像TextView试图设置的值总是第一个(ListView的第一个元素)。

任何想法???

1 个答案:

答案 0 :(得分:0)

看看这个:

Category cat = mCategoriesList.get(position);
tvCategory.setText(cat.getName());
if(!cat.isInitialized()) //<-- If I delete this line it works, but inefficienly, as the AsyncTask is launched many times repeatedly
{
    cat.setIsInitialized(true)
    new GetNewsForCategoryTask(cat, tvUnreadNews, mContext).execute(cat.getId());
}

我认为您必须在setIsInitialized(true)上致电mCategoriesList.get(position),而不是cat,因为再次调用getView()时,mCategoriesList.get(position)始终会返回未初始化的setIsInitialized(true) ,因为您在cat上呼叫mCategoriesList,而不是{{1}}。