Skip to content Skip to sidebar Skip to footer

Google Maps Android Indexoutofboundsexception

I am trying to get markers placed on the map and fly to their destination. within a forloop i have an if statement, i wish it to do this: for(i loop){ If (array(i) == null{ spawn p

Solution 1:

You can use Map<Integer, Marker> (Integer are keys and Marker are values). Then you can leverage Map.get() which don't throws Exception if key is Integer and not null (your i will not be null in your code).

Declare markers as Map:

Map<Integer, Marker> markers = new HashMap<Integer, Marker>();

Inside CreateMarker.run() after final LatLng position = new LatLng(crLat,crLon); change as follows:

//implicit boxing to use int in MapIntegerii= Integer.valueOf(i);

//try to get marker by index from map (index is the key)MarkermarkerByIndex= markers.get(ii);

//Map.get() returns null if object by specified key is not in mapif (markerByIndex == null){
    //marker doesn't exists - create it, add to Google Map and to Map by key
    timm += 1;
    runOnUiThread(newRunnable() {
        @Overridepublicvoidrun() {
            finalMarkermarker=  mMap.addMarker(newMarkerOptions()
                                   .position(newLatLng(depLat, depLon))
                                   .title("Hello world")
                                   .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));

            //put marker to map using i as a key
            markers.put(ii, marker);
        }
    });
} else {
    //marker exists, mutate it
    markerByIndex.setPosition(position);
    markerByIndex.setVisible(false);

    //...replace the marker in map
    markers.put(ii, markerByIndex);

    //animate the marker
    animateMarker(markerByIndex, position , true, spd);
}

Solution 2:

You wrote:

i understand that the markers.get(i) is causing the problem, but i dont know how to check if the markers array is null without it throwing this error.

==> you can check it this way:

if (markers != null && markers.size() > 0) {
      //there are actually markers. Calling markers.get(i) should work! //...as long as i is smaller than markers.size()
} else {
      //sorry, no markers! Don't call markers.get(i) here...
}

Post a Comment for "Google Maps Android Indexoutofboundsexception"