0

In Xamarin, how can I convert a return type of 'System.Threading.Tasks.Task<Android.Graphics.Bitmap>' to 'Android.Graphics.Bitmap'

Here is my method:

private async Task<Bitmap> GetBitmapFromUriAsync(string uri)
{
    var client = new HttpClient();

    using (var data = await client.GetStreamAsync(uri))
    {
        if (data != null && data.Length > 0)
        {
            return await BitmapFactory.DecodeStreamAsync(data);
        }
    }

    return null;
}

I am needing to set the result of the above method to an ImageView

This is the code that I currently have:

gridViewItem.image = GetBitmapFromUriAsync("http://image.png");

Here is the error:

Cannot implicitly convert type 'System.Threading.Tasks.Task<Android.Graphics.Bitmap>' to 'Android.Graphics.Bitmap'

Thanks in advance

EDIT

I have added the await keyword as follows: gridViewItem.image = await GetBitmapFromUriAsync("http://image.png");

This is the error that I am getting:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

How do I modify the return type to be Task, yet still return a Bitmap?

1
  • 1
    The error you are getting is descriptive enough. You have to make the method in which GetBitmapFromUriAsync("http://image.png"); is called async Commented Jun 17, 2014 at 10:22

2 Answers 2

1

Calling

gridViewItem.image = GetBitmapFromUriAsync("http://image.png").Result;

will give you the bitmap, but will do it synchronously. If you want to take advantage of the asynchronous calls in .NET 4.5, you should call

gridViewItem.image = await GetBitmapFromUriAsync("http://image.png");
Sign up to request clarification or add additional context in comments.

Comments

0

have you tried something like this?

gridViewItem.image = GetBitmapFromUriAsync("http://image.png").Result;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.