安卓 : Load asynchronous pictures in listView

标签 android listview android-asynctask adapter

我想显示一个带有自定义适配器(带有图片和文本)的 ListView。

图像是从远程服务器加载的,所以我决定使用 AsyncTask。

实际上,图片显示的很好,但是如果我快速向下滚动,在 1/2 秒内显示错误的图片(加载后,正确的图片出现)

这是我的适配器代码:

public class GiAdapter extends BaseAdapter {

    private Context mContext;

    private List<SiteStaff> mListAppInfo;
    private HashMap<Integer, ImageView> views;
    private HashMap<String,Bitmap> oldPicts = new  HashMap<String,Bitmap>();
    private LayoutInflater mInflater;
    private boolean auto;

    private final String BUNDLE_URL = "url";
    private final String BUNDLE_BM = "bm";
    private final String BUNDLE_POS = "pos";
    private final String BUNDLE_ID = "id";

    public GiAdapter(Context context, List<SiteStaff> list) {
        mContext = context;
        mListAppInfo = list;
        views = new HashMap<Integer, ImageView>();
        mInflater = LayoutInflater.from(mContext);

    }

    @Override
    public int getCount() {
        return mListAppInfo.size();
    }

    @Override
    public Object getItem(int position) {
        return mListAppInfo.get(position).getId();
    }

    @Override
    public long getItemId(int position) {
        return mListAppInfo.get(position).getId();
    }

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

        LinearLayout layoutItem;

        // reuse of convertView
        if (convertView == null) {
            layoutItem = (LinearLayout) mInflater.inflate(R.layout.auto_gi, parent, false);
        } else {
            layoutItem = (LinearLayout) convertView;
        }

        // infos for the current element
        SiteStaff entry = mListAppInfo.get(position);

        //set some text fields
        TextView name = (TextView) layoutItem.findViewById(R.id.name);
        TextView size = (TextView) layoutItem.findViewById(R.id.size); 

        name.setText(entry.getName());
        size.setText(entry.getSize());

        // get the imageView for the current object
        ImageView v = (ImageView) layoutItem.findViewById(R.id.gi_image);

        // put infos in bundle and send to the LoadImage class
        Bundle b = new Bundle();

        //url of the pict
        b.putString(BUNDLE_URL, entry.getUrl());

        //position in the listView
        b.putInt(BUNDLE_POS, position);

        //id of the current object
        b.putInt(BUNDLE_ID, entry.getId());

        //put info in the map in order to display in the onPostExecute
        views.put(position, v);

        // thread
        new LoadImage().execute(b);

        return layoutItem;

    }

    //asyncTackClass for loadingpictures
    private class LoadImage extends AsyncTask<Bundle, Void, Bundle> {

        @Override
        protected Bundle doInBackground(Bundle... b) {

            Bitmap bm =null;

            //cache: for better performance, check if url alredy exists
            if(oldPicts.get(b[0].getString(BUNDLE_URL))==null){
                bm = Utils.getBitMapFromUrl(b[0].getString(BUNDLE_URL));
                oldPicts.put(b[0].getString(BUNDLE_URL),bm);
            }else{
                bm = oldPicts.get(b[0].getString(BUNDLE_URL));
            }

            // get info from bundle
            Bundle bundle = new Bundle();
            bundle.putParcelable(BUNDLE_BM, bm);
            bundle.putInt(BUNDLE_POS, b[0].getInt(BUNDLE_POS));

            return bundle;

        }

        @Override
        protected void onPostExecute(Bundle result) {
            super.onPostExecute(result);

            //get picture saved in the map + set
            ImageView view = views.get(result.getInt(BUNDLE_POS));
            Bitmap bm = (Bitmap) result.getParcelable(BUNDLE_BM);

            if (bm != null){ //if bitmap exists...
                view.setImageBitmap(bm);
            }else{ //if not picture, display the default ressource
                view.setImageResource(R.drawable.unknow);
            }

        }

    }

}

谢谢!

最佳答案

就像 Shubhayu 提到的,您在 ListView 行中看到错误的图像,因为您的适配器正在回收一个 View 来构造每一行,而您的异步任务正在维护对该回收 View 的引用。当您的任务完成时,它们将更新 ImageView,此时它实际上可能对应于其他一些行。

在每次调用 getView 时扩充新 View 的问题在于,滚动时 ListView 的性能会很差。您(正确地)使用 convertView 来减少这种开销,您只是错过了将 ImageView 正确绑定(bind)到 Async 的部分。我在这里找到了解决方案:http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

总而言之,它基本上是扩展一个 Drawable 来封装一个任务,并且只有在任务适本地绑定(bind)到图像时才更新图像。 “处理并发”部分解决了您面临的问题。特别是,阅读该部分之前的段落,了解导致问题的原因的摘要。

关于安卓 : Load asynchronous pictures in listView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9832944/

相关文章:

java - MediaRecorder.start() 抛出 IllegalStateException

android - Android 内存调试教程或示例

android - BackUpAgentHelperClass 没有被调用

android - 更新 ListView 内的 ImageView

java - 无法在 ListView 上执行 onClick 操作

java - BaseExpandableListAdapter 中的不可扩展项目

Android 如何在 onDestroy() 后重新连接到 AsyncTask 并重新启动 onCreate()?

java - findFragmentByTag 中的 Null 检查与 Objects.requireNonNull

java - 在自定义内容通知中使用后更新 RemoteView

android - 更新 Android 中方向变化的进度条