1

I am new to Xamarin Android and i am developing just simple app for fetching and displaying image from server. Here is my code-

 public void testWCF2()
        {
            var imgView = FindViewById<ImageView>(Resource.Id.imageView123);
            using(var bm = await GetImageFromUrl(@"http://xamarin.com/content/images/pages/forms/example-app.png"))    //At this line an error is showing 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'. 
                imgView.SetImageBitmap(bm);

        }

    private async Task<Bitmap> GetImageFromUrl(string url)
    {
        using(var client = new HttpClient())
        {
            var msg = await client.GetAsync(url);
            if (msg.IsSuccessStatusCode)
            {
                using(var stream = await msg.Content.ReadAsStreamAsync())
                {
                    var bitmap = await BitmapFactory.DecodeStreamAsync(stream);
                    return bitmap;
                }
            }
        }
        return null;
    }

Someone please help me.

Thanks

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
Ritesh Gupta
  • 171
  • 1
  • 2
  • 19

1 Answers1

4

You need to add async modifier to your method like :

        public async void testWCF2()
        {
            var imgView = FindViewById<ImageView>(Resource.Id.imageView123);
            using(var bm = await GetImageFromUrl(@"http://xamarin.com/content/images/pages/forms/example-app.png"))    
                imgView.SetImageBitmap(bm);
        }

MSDN says:

Use the async modifier to specify that a method lambda expression, or anonymous method is asynchronous. If you use this modifier on a method or expression, it's referred to as an async method.

puko
  • 2,819
  • 4
  • 18
  • 27
  • The error has gone but still the image of given url is not displaying on ImageView. What may be the reason. if you have any code then please specify – Ritesh Gupta Mar 27 '15 at 11:44
  • try to debug if your method GetImageFromUrl returned anything ... – puko Mar 27 '15 at 11:47
  • I have debug GetImageFromUrl method. Its returning null value. Also app get crashes and giving the following error while debuging-System.Diagnostics.Debugger.Mono_UnhandledException_internal () – Ritesh Gupta Mar 27 '15 at 12:17
  • so that is the problem ... but your question is about async modifier ... – puko Mar 27 '15 at 12:47
  • my problem about async has resolved. I want to show image on ImageView from server. Code is shown above, But nothing is displaying and also app get crashes when GetImageFromUrl run. – Ritesh Gupta Mar 28 '15 at 05:56