1

I'm trying to iterate through a hashmap and and use the key during my iteration. I decided to use it inside an Async Task because the iteration was blocking my UI thread.

My hashmap has LatLng as the Key and a Marker as the Object, when I get the key during Iteration and pass it to a new LatLng that works fine but when I try to use this new LatLng I get a java.util.ConcurrentModificationException exception. Strangely this doesn't happen when I use the code without the AsyncTask

Here is my code

    class AddCityMarker extends AsyncTask<Integer, Integer, String> {

    protected String doInBackground(Integer... counter) {           

        //CityMarker cMarker;
        LatLng marker_loc;

        List<String> city_markers = new ArrayList<String>();
        if(displayed.size() > 0){

            Iterator<HashMap.Entry<LatLng, Marker>> myIterator = displayed.entrySet().iterator();
            while(myIterator.hasNext()) {
                //cMarker = new CityMarker();
                HashMap.Entry<LatLng, Marker> entry = myIterator.next();                    
                marker_loc = entry.getKey();

                Log.i("ZOOM", "Key = " + marker_loc + ", Value = " + entry.getValue());

                List<Address> addresses = null;                     
                try {
                  //This is where I get the error
                    addresses = gcode.getFromLocation(marker_loc.latitude, marker_loc.longitude, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if(addresses.size() > 0) {  
                    if(!city_markers.contains(addresses.get(0).getLocality())){
                        city_markers.add(addresses.get(0).getLocality());
                        //map.addMarker(new MarkerOptions().position(marker_loc).snippet("CITY"));
                    }                           
                }
            }                   
        }


        return null;
    }

    protected void onPostExecute(String jsonResult) {

        try {   

            if(isClubMarkers){
                map.clear();
                isClubMarkers = false;
            }
            displayed.clear();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4

1 回答 1

1

从 Android 1.6 到 Android HoneyComb,异步任务以并行模式运行。这意味着像不同的线程。在您的情况下,有时您可能会多次调用异步任务,并且他们可能会尝试访问相同的 HashMap 进行迭代。您可以通过使用“ConcurrentHashMap”而不是 HashMap 来避免此异常。但正确的方法是确定异步任务是否多次调用,如果存在则尽量避免它。如果您在异步任务迭代时尝试使用 Hashmap 进行操作,也会发生这种情况。如果是这种情况,请使用线程安全的“ConcurrentHashMap”。

于 2013-08-12T11:24:13.833 回答