I have a method that adds many Markers to a Google Map.
Here is my code:
item = new MapLocation();
URL myurl = new URL("http://www.canninginc.co.nz/CanFindLocation/yes.png");
Bitmap bmp = BitmapFactory.DecodeStream(myurl.OpenConnection().InputStream);
item.icon = BitmapDescriptorFactory.FromBitmap(bmp);
item.Location = new LatLng (-41.227834, 174.812857);
item.Snippet = "Snippet2";
item.Title = "Title2";
item.ShowInfoWindowOnStartup = true;
_mapLocationList.Add(item);
I am getting this error:
Exception of type 'Android.OS.NetworkOnMainThreadException' was thrown.
I have done some research and I think I need to run the action on another thread when getting the Bitmap.
Can I have some help with this code? Does the AsyncTask return a Bitmap, or how do I tie the two together?
Thanks in advance.
EDIT
I am using Xamarin, and have posted the following code into a new class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
namespace SimpleMapDemo
{
class MyAsyncTask extends AsyncTask<String, Void, Bitmap>
{
@Override
protected Bitmap doInBackground(String... urls) {
if (urls.length > 0) {
URL myurl = new URL("http://www.canninginc.co.nz/CanFindLocation/yes.png");
return BitmapFactory.DecodeStream(myurl.OpenConnection().InputStream);
}
return null;
}
@Override
protected void onPostExecute(Bitmap bmp) {
super.onPostExecute(bmp);
if (bmp != null) {
item = new MapLocation();
item.icon = BitmapDescriptorFactory.FromBitmap(bmp);
item.Location = new LatLng (-41.227834, 174.812857);
item.Snippet = "Snippet2";
item.Title = "Title2";
item.ShowInfoWindowOnStartup = true;
_mapLocationList.Add(item);
}
}
}
}
I am getting many errors. Am I placing this code in the correct area?
@Overrideandextendsare Java words. In C#,you need to change them, e.g.overridein declaration and using:. Or alternatively, you may look at this Async Support Overview in Xamarin