【问题标题】:ListView not showing image from URL on initial list load but only when items are scrolled of and on the screenListView 在初始列表加载时不显示来自 URL 的图像,但仅当项目在屏幕上滚动时显示
【发布时间】:2014-08-07 14:05:08
【问题描述】:

在自定义小部件 Horizo​​ntalListView 中,我正在显示来自 URL 的图像。

问题是对于这个 ListView 图像中的每个项目,只有当项目第二次出现在屏幕上时才会从 URL 加载,这可能意味着视图被回收后。为什么第一次显示视图项时没有加载 URL 图像我不知道。起初以为可能是自定义视图问题,但我尝试使用常规 ListView 以同样的问题结束。

为了加载图像,我使用的是我在网上找到的 ImageLoader。我现在坚持了大约 7-8 小时,如果有任何帮助,我们将不胜感激

这是适配器:

public class ItemPreviewAdapter extends ArrayAdapter<HashMap<String, String>> {

    private final List<HashMap<String, String>> items;
    private final LayoutInflater mLayoutInflater;
    ImageLoader imgLoader;


    static class ViewHolder {
        TextView item_name;
        TextView item_price;
        ImageView image;
    }

    public ItemPreviewAdapter(final Context context, final int textViewResourceId, List<HashMap<String, String>> map) {
        super(context, textViewResourceId);
        mLayoutInflater = LayoutInflater.from(context);
        imgLoader = new ImageLoader(context);
        this.items = map;
        }

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

        ViewHolder holder;

        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.lvitem_homepage_item, parent, false);

            holder = new ViewHolder();
            holder.item_name = (TextView) convertView.findViewById(R.id.tvItemName);
            holder.item_price = (TextView) convertView.findViewById(R.id.tvItemPrice);
            holder.image = (ImageView) convertView.findViewById(R.id.ivItemImage);

            convertView.setTag(holder);
        } 

        holder = (ViewHolder) convertView.getTag();


        HashMap<String, String> item = items.get(position);

        String id = item.get("id");
        String item_name = item.get("iname").toUpperCase();
        String item_price = item.get("new_price").toUpperCase();
        String currency = item.get("currency").toUpperCase();


        holder.item_name.setText(item_name);
        holder.item_price.setText(item_price+" "+currency);

        String image_url = "http://www.mywebsite.com/images/items/cropped_image_list_id_"+ id + ".png";
        imgLoader.DisplayImage(image_url, holder.image);

        return convertView;
    }
}

图像加载器:

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.ic_launcher;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);


        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            // imageView.setImageResource(stub_id);
        }


    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // from web
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 1;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            Object tag = photoToLoad.imageView.getTag();
            if(tag != null && ((String)tag).equals(photoToLoad.url)){
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                Activity a = (Activity) photoToLoad.imageView.getContext();
                a.runOnUiThread(bd);
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

任务:

private class LatestItems extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... loc_id) {

        // For storing data from web service
        String data = "";

        // Downloader object
        UrlDownloader downloader = new UrlDownloader();

        // Building the url to the web service
        String url = "http://www.mywebsite.com/web_services/home_screen_latest_items.php?loc_id="
                + loc_id[0];

        try {
            // Fetching the data from web service in background
            data = downloader.downloadUrl(url);

        } catch (Exception e) {
            Log.d("Downloader exception", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String downloadedData) {
        super.onPostExecute(downloadedData);

        //If web service returned data
        if (downloadedData != null) {
            JSONObject jObject;

            // Instantiate parser
            ItemJSONParser itemsParser = new ItemJSONParser();

            try {
                // Put data into JSON Object and pass it to parser
                jObject = new JSONObject(downloadedData);
                items = itemsParser.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }

            // Instantiate adapter. Provide Context, Item layout and
            // DataSource (result)
            ItemPreviewAdapter itemPreview = new ItemPreviewAdapter(
                    getApplicationContext(), R.layout.lvitem_homepage_item,
                    items);

            // Pass each data to from list into to adapter
            for (HashMap<String, String> data : items) {
                itemPreview.add(data);
            }

            // Set adapter
            latestItemsList.setAdapter(itemPreview);
        }
    }

}

【问题讨论】:

  • 很高兴您使用 asynctask 编写了自己的图像加载器实现,但使用像 VolleyPicasso 这样的图像加载库可能更容易。使用 volley,您必须自己实现 som 东西。使用 Picasso,您可以用 1 行代码替换 ImageLoader 类,该代码将图像加载和缓存到磁盘/内存和图像占位符以及错误图像Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

标签: android listview android-listview


【解决方案1】:

在设置适配器后尝试在异步任务的 onPostExecute() 中执行itemPreview.notifyDataSetChanged()

【讨论】:

    【解决方案2】:

    这里您没有将列表绑定到父级:

    替换

    public ItemPreviewAdapter(final Context context, final int textViewResourceId, List<HashMap<String, String>> map) {
            super(context, textViewResourceId);
            ....
            }
    

     public ItemPreviewAdapter(final Context context, final int textViewResourceId, List<HashMap<String, String>> map) {
            super(context, textViewResourceId,map);
            ....
            }
    

    还有一件事

    if (convertView == null) {
                 .....
                convertView.setTag(holder);
            } else{
    
            holder = (ViewHolder) convertView.getTag();
    
    }
    

    获取 holdertag 时添加 else..

    就是这样……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      相关资源
      最近更新 更多