I'm adding markers to my map from a url using the Picasso library
As a marker isn't an ImageView I tried to use a Target instead
for(int x =0; x < mapIcon_url.length; x++){
Picasso.with(getActivity()).load(mapIcon_url[x]).resize(marker_size, marker_size+15).into(new Target() {
@Override
public void onSuccess(Bitmap b) {
bitmapMarker = BitmapDescriptorFactory.fromBitmap(b);
//create marker option
if(b != null)
markerOptions = new MarkerOptions().position(marker_position).icon(bitmapMarker));
else
markerOptions = new MarkerOptions().position(marker_position).icon(BitmapDescriptorFactory.fromResource(R.drawable.placeholder_pin)).snippet(String.valueOf(x));
marker = map.addMarker(markerOptions);
}
@Override
public void onError() {
//create marker option
markerOptions = new MarkerOptions().position(marker_position).icon(BitmapDescriptorFactory.fromResource(R.drawable.placeholder_pin)).snippet(String.valueOf(x));
marker = map.addMarker(markerOptions);
}
});
}
I'm doing this in a loop to add about 20 markers but I find that on first run of the code only 5 or 7 markers are added so I've switched to using the lib and an AsyncTask like this.
for(int x =0; x < mapIcon_url.length; x++){
new AddMarker().execute(mapIcon_url[x]);
}
public class AddMarker extends AsyncTask<String, Integer, BitmapDescriptor> {
BitmapDescriptor bitmapMarker1;
VenueDetails myVenue;
@Override
protected BitmapDescriptor doInBackground(String... url) {
myUrl = url[0];
try {
bitmapMarker1 = BitmapDescriptorFactory.fromBitmap(Picasso.with(getActivity()).load(myUrl).resize(marker_size, marker_size+15).get());
} catch (IOException e) {
e.printStackTrace();
}
return bitmapMarker1;
}
protected void onPostExecute(BitmapDescriptor icon) {
try {
map.addMarker(new MarkerOptions().position(marker_position).icon(icon)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
However I'm a bit worried this method could give me some issues when I have alot of markers say about 100. My question would be is this the best way to do this and if not what other options can I try.
Target
might be coming garbage collected and thats why you lose some of the downloads. – BikolmapIcon_url.length
size. Store yourTarget
instances into the array. Once download is complete, remove from the array (remember to remove also if the download failed). If the user exits yourActivity
loop through the array and callcancelRequest(array[i])
to cancel all pending/in-progress requests. You must keep a strong reference to yourTarget
, otherwise there is a high chance it will get gc'ed. – BikolAsyncTask
. Its implementation for execution (parallel vs sequential) has changed over Android versions and I would avoid spawning so many threads. Picasso will do the work for you just fine. – BikolTarget
. – Bikol