3

I have a ListView of multiple items and each item in the list should have an image associated with it. I have created an Array Adapter to hold each list item and have the url of the image I wish to load.

I am trying to asynchronously load the image using a web request and have it set the image and update it in the view once it has been loaded but the view should render immediatly with a default image.

Here is the method I am using to try to load the image

private async Task<Bitmap> GetImageBitmapFromUrl(string url, ImageView imageView)
{
    Bitmap imageBitmap = null;

    try
    {
        var uri = new Uri(url);
        var response = httpClient.GetAsync(uri).Result;

        if (response.IsSuccessStatusCode)
        {
            var imageBytes = await response.Content.ReadAsByteArrayAsync();
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                imageView.SetImageBitmap(imageBitmap);
            }
       }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    return imageBitmap;
}

I am initializing my HttpClient like so:

httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 10);
httpClient.MaxResponseContentBufferSize = 256000;

And here is how I am calling the GetImageFromUrl Method

ImageView myImage = convertView.FindViewById<ImageView>(Resource.Id.AsyncImageView)
myImage.SetImageBitmap(null);
string url = GetItem(position);
GetImageBitmapFromUrl(url, myImage);

Using this code the request eventually comes back with a bad request but when I view the url I am using and paste it into a browser window it brings up the image I am expecting.

1 Answer 1

11

You don't need to care about downloading images.

There exist two good libraries to load an image into a ImageView async in Xamarin.Android.

Picasso component (source) usage:

Picasso.With(context)
       .Load("http://i.imgur.com/DvpvklR.png")
       .Into(imageView);

FFImageLoading (source) usage:

ImageService.Instance.LoadUrl(urlToImage).Into(_imageView);

Note (from documentation):

Unlike Picasso you cannot use FFImageLoading with standard ImageViews. Instead simply load your images into ImageViewAsync instances. Updating your code is very easy since ImageViewAsync inherits from ImageView.

Sign up to request clarification or add additional context in comments.

2 Comments

I went with the Picasso solution. Thank you for your quick response!
nuget is square.picasso

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.