从url异步加载图像以填充列表视图



我目前在异步图像加载以填充"无限"列表视图(从url加载数据并存储在自定义适配器中)方面遇到了一些小问题。我找到了ImageView的这个扩展方法,它基本上是koush/UrlImageViewHelper的端口,但原始的更新了很多,端口已经9个月没有更新了。。。当我在自定义适配器中填充ImageView时,一切似乎都很好,速度很快(我从速度很快的服务器上下载小图像),但在大约200个图像(每个15-20kb大小)之后,下载就停止了。我认为问题出在图像缓存上,但即使使用扩展中提供的"清理"方法,也没有任何变化。有人知道如何解决这个问题,或者有更好的解决方案吗?我试着创建自己的"队列",但它有另一种问题——当滚动列表视图时,任何新的ImageView都已经有了源图像,这会更改为正确的图像,但快速滚动时,这看起来非常糟糕。这是我的代码:

在我的自定义列表适配器中获取视图

public override View GetView(int position, View convertView, ViewGroup parent)
{
    //Populating the adapter with new items
    if (position >= this._items.Count - 1)
        ThreadPool.QueueUserWorkItem(o => this.LoadPage());
    var item = this._items[position];
    View view = convertView;
    if (view == null)
        view = this._context.LayoutInflater.Inflate(Resource.Layout.CustomRowView, null);
    var imgUrl = string.Format(@"http://myserver.com/?action={0}&url={1}", "get.thumbnail", item.Image.Url);
    //Here is the image loading row
    view.FindViewById<ImageView>(Resource.Id.imageView1).SetUrlDrawable(imgUrl);
    view.FindViewById<TextView>(Resource.Id.txtTitle).Text = item.Title;
    view.FindViewById<TextView>(Resource.Id.txtYear).Text = item.Information.Year;
    view.FindViewById<TextView>(Resource.Id.txtGenre).Text = item.Information.Genre;
    view.FindViewById<TextView>(Resource.Id.txtGrade).Text = item.Rating.Grade;
    view.FindViewById<TextView>(Resource.Id.txtVotes).Text = string.Format("( {0} )", item.Rating.Votes);
    return view;
}

LoadPage函数

public void LoadPage()
{
    OnUpdateAnimeListStart(); //Event to display loading message
    try
    {
        this._items.FillListFromUrl(string.Format("http://myserver.com/page/{0}/", this._page));
    }
    catch(Exception ex)
    {
        _context.RunOnUiThread(() =>
        {
            new AlertDialog.Builder(_context)
                .SetPositiveButton("Ok", (sender, args) =>
                {
                    Intent blankIntent = new Intent();
                    blankIntent.SetFlags(ActivityFlags.ClearTop);
                    int intPID = Android.OS.Process.MyPid();
                    Android.OS.Process.KillProcess(intPID);
                })
                .SetMessage(ex.Message)
                .SetTitle("Error!")
                .Show();
        });
    }
    this._page++;
    _context.RunOnUiThread(() =>
    {
        _context.FindViewById<ListView>(Resource.Id.listView).InvalidateViews();
    });
    OnUpdateAnimeListEnd(); //Event to hide loading message
}

这是我的另一个"队列",我谈到过

    public class ImageDownloader
    {
        private List<ImageView> _queueImageViews;
        private List<string> _queueImageUrls;
        private Activity _context;
        public ImageDownloader(Activity context)
        {
            this._context = context;
            this._queueImageViews = new List<ImageView>();
            this._queueImageUrls = new List<string>();
        }
        public void DownloadImage(ImageView imgView, string url)
        {
            this._queueImageViews.Add(imgView);
            this._queueImageUrls.Add(url);
            if (this._queueImageViews.Count == 1)
                this._startJob();
        }
        private void _startJob()
        {
            WebClient web = new WebClient();
            web.DownloadDataCompleted += new DownloadDataCompletedEventHandler(web_DownloadDataCompleted);
            web.DownloadDataAsync(new Uri(this._queueImageUrls[0]));
        }
        private void _removeFromeQueue(int index = 0)
        {
            this._queueImageUrls.Remove(this._queueImageUrls[index]);
            this._queueImageViews.Remove(this._queueImageViews[index]);
        }
        void web_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            ImageView v = this._queueImageViews[0];
            this._context.RunOnUiThread(() =>
            {
                Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);
                v.SetImageBitmap(bm);
            });
            this._removeFromeQueue();
            if (this._queueImageViews.Count > 0)
                this._startJob();
        }
    }

提前谢谢。

由于在UrlImageViewHelper端口中进行了更多的调试,解决了我的问题。正如我所设想的,问题出在缓存上。背后的逻辑是将缓存项限制为特定数量(我不知道为什么,但它是硬编码的),如果达到了限制,则需要从缓存中删除前几个项。这很好,但是实现仍然存在一些错误。目前,我没有进行更多的调试和修复实现,而是将限制增加到5000(最初设置为100),但这只是解决这个问题的临时方法。将来我可能会修复代码,这样它就会删除缓存集合中的第一个项。现在是:

SoftReferenceHashTable<TKey, TValue>

修复了这条线:LRUCache<TKey, TValue> cache = new LRUCache<TKey, TValue>(100);
对此:LRUCache<TKey, TValue> cache = new LRUCache<TKey, TValue>(5000);


此外,由于@Y2i的评论,我发现在UrlImageViewHelper类中,在SetUrlDrawable方法中,下载是在不关闭互联网连接的情况下实现的。也许这不是什么大问题,但我更愿意解决这个问题。所以我更改了代码的这一部分:

var client = new System.Net.WebClient();
var data = client.DownloadData(url);
System.IO.File.WriteAllBytes(filename, data);
return LoadDrawableFromFile(context, filename);

对此:

using (var client = new System.Net.WebClient())
{
    var data = client.DownloadData(url);
    System.IO.File.WriteAllBytes(filename, data);
    return LoadDrawableFromFile(context, filename);
}

我有一个类似的问题,这就是我的答案。koush/UrlImageViewHelper的Mondroid版本也给我带来了问题。所以我把它拆开,重建了我自己的版本。希望有人会发现这很有用。

http://xandroid4net.blogspot.com/2014/09/xamarinandroid-loading-images-from-web.html

最新更新