2012-01-05 68 views
3

我正在使用MapView,它需要添加多個覆蓋項目。我發現添加覆蓋項目速度很慢,導致地圖拖到ANR時。所以我構建了一個AsyncTask來添加重疊項。最初,我發現它一直失敗,因爲我從後臺線程訪問覆蓋集合,並且我收集它不是線程安全的。所以我改變了它,所以覆蓋只是從UI線程改變。它現在可以工作,但只有大部分時間。當地圖被觸摸時,它偶爾會崩潰。如何從AsyncTask更新MapView覆蓋項目而無ArrayIndexOutOfBoundsException

這裏的的AsyncTask(我MapView類的子類中的內部類):

class showItemsTask extends AsyncTask<Void, User, Void> { 

public boolean stop = false; 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
} 

protected Void doInBackground(Void... v) { 
    User[] items = Item.getItemList(); 
    if (items != null && items.length > 0) { 
     int i = 0; 
     for (User item : items) { 
      publishProgress(item); 
      i++; 
      if (stop || i>MAX_NUMBER_OF_ITEMS) break; 
     } 
     stop = false; 
    } 
    return null; 
} 

@Override 
protected void onProgressUpdate(User... itemContainer) { 
    super.onProgressUpdate(itemContainer); 
    User item = itemContainer[0]; 
    showItem(item.location.latitude, item.location.longitude, item.location.firstname, ((Integer) item.location.id).toString()); 
} 

public void showItem(float latitude, float longitude, String itemTitle, String itemSubtitle) { 
    try { 
     GeoPoint point = new GeoPoint((int) (latitude * 1000000), (int) (longitude * 1000000)); 
     OverlayItem marker = new OverlayItem(point, itemTitle, itemSubtitle); 
     availableItemsOverlay.addOverlay(marker); 
    } catch (Exception e) { 
     Trace.e(TAG, "Exception drawing a item"); 
    } 
} 

protected void onPostExecute(Void v) { 
    invalidate(); 
} 


} 

這裏的堆棧跟蹤:

0 java.lang.ArrayIndexOutOfBoundsException 
1 at com.google.android.maps.ItemizedOverlay.maskHelper(ItemizedOverlay.java:562) 
2 at com.google.android.maps.ItemizedOverlay.setFocus(ItemizedOverlay.java:365) 
3 at com.google.android.maps.ItemizedOverlay.focus(ItemizedOverlay.java:539) 
4 at com.google.android.maps.ItemizedOverlay.onTap(ItemizedOverlay.java:455) 
5 at com.google.android.maps.OverlayBundle.onTap(OverlayBundle.java:83) 

我要去下來的AsyncTask在錯誤的道路?如果沒有,你能看到爲什麼我得到這個異常,當在UI線程中進行覆蓋的所有更改時?

+0

您是否碰巧了解mapView未失效的確切原因? 我有類似的問題:http://stackoverflow.com/questions/23011264/mapview-doesnt-invalidate-onprogressupdated-of-async-task – zIronManBox 2014-04-14 05:58:06

回答

0

我想你必須在更新覆蓋圖後(在availableItemsOverlay.addOverlay(marker)之後)調用地圖視圖的postInvaliadate()。

0

雖然onProgressUpdate()runs on the UI thread我不確定是否用於添加疊加項目。相反,我建議在onPostExecute()中添加疊加層。 add()操作並不昂貴,因爲在此時已經生成了項目列表。

@Override 
protected void onPostExecute(List<OverlayItem> overlay) { 
    mMapView.getOverlays().add(overlay); 
    mMapView.invalidate(); 
} 

你需要你AsyncTask簽名更改爲AsyncTask<Void, User, List<OverlayItem>>爲了匹配方法。

+0

也可以看看:http://stackoverflow.com/questions/23011264/mapview-doesnt-invalidate-onprogressupdated-of-async-task 我有類似的問題 – zIronManBox 2014-04-14 05:59:02