samedi 28 mars 2015

Fetch Image from Server in Xamarin Android

I am trying to fetch an image from server and to display on ImageView control in my Xamarin Android. I have tried to method for doing it but none of them is working. What may be the reason? Please help me


METHOD -I



public void testWCF()
{
WebClient web = new WebClient();
web.DownloadDataCompleted += new DownloadDataCompletedEventHandler(web_DownloadDataCompleted);
web.DownloadDataAsync(new Uri(@"http://ift.tt/191hiVP"));

}

void web_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{

if (e.Error != null)
{
RunOnUiThread(() =>
Toast.MakeText(this,"ritesh your error is "+ e.Error.Message, ToastLength.Long).Show());
}
else
{

Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);

RunOnUiThread(() =>
{
ImageView imgView = FindViewById<ImageView>(Resource.Id.imageView1);
imgView.SetImageBitmap(bm);
});
}
}


METHOD-II



public async void testWCF2()
{
var imgView = FindViewById<ImageView>(Resource.Id.imageView1);
using(var bm = await GetImageFromUrl(@"http://ift.tt/191hiVP"))
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;
}




Aucun commentaire:

Enregistrer un commentaire