2014-05-08 57 views
0

我的代碼應該檢查LatLng是否在距離當前LatLng 3000米之內。如果是,程序應該在地圖上放置一個標記。但由於某種原因,它卡在無限的for循環中。卡在無限循環

public void onStart() { 
... 
Log.d("how big is compareloc", "size "+compareLocations().size());// outputs : 4 
      for(int mm=0;mm<compareLocations().size();mm++){ 
       HashMap<String, LatLng> test = compareLocations().get(mm); 
       Log.d("LatLng positon", "marker pos "+test.get(TAG_LATLNG)); 
        if(test.get(TAG_LATLNG)!=null){ 
       googleMap.addMarker(new MarkerOptions().position(test.get(TAG_LATLNG)).title("test")); 
        } 
      } 
... 
} 

這是我compareLocations()這我經緯度與latlngs的列表進行比較:

public ArrayList<HashMap<String, LatLng>> compareLocations(){ 
     LatLng mLocation; 
     gps = new GPSTracker(getActivity()); 
      if(gps.canGetLocation()) { 
       double latitude = gps.getLatitude(); 
       double longitude = gps.getLongitude(); 
       mLocation = new LatLng(latitude, longitude); 
       Location mylocation = new Location("Test1"); 
       mylocation.setLatitude(mLocation.latitude); 
       mylocation.setLongitude(mLocation.longitude); 


       mdatabase.open(); 
     Cursor cCompare=mdatabase.getAllItems(); 
     for(int melon=0;melon<cCompare.getCount();melon++){ 
      HashMap<String, LatLng> points = new HashMap<String, LatLng>(); 
      double DBlat = mdatabase.getlat(melon); 
      double DBlong = mdatabase.getlong(melon); 
      LatLng myco = new LatLng(DBlat, DBlong); 
      Location location = new Location("Test"); 
       location.setLatitude(myco.latitude); 
       location.setLongitude(myco.longitude); 
       if(mylocation.distanceTo(location)<=3000){ 
        points.put(TAG_LATLNG, myco); 
        Log.d("Checking distance", "distance less than 300 meters"); 
       }else{ 
       Log.d("Checking distance", "distance is greater than 300 meters"); 
       } 
       closelist.add(points); 
      } 
      mdatabase.close(); 
      } else { 
       gps.showSettingsAlert(); 
      } 
     return closelist; 
    } 
+0

我會建議選擇一種更具可讀性的代碼風格。儘管選擇這些內容很大程度上是個人偏好的問題,但我在閱讀代碼時非常困難。諸如在分號之後放置空格,而分號之前的括號和其他文本之間的括號之前的空格和空格之間放置空格將會很長。這也可能有助於解決像'if(gps.canGetLocation())'似乎缺少一個右括號,儘管它有一個開放的問題 - 我自己更喜歡括號 - 自己的線樣式,因爲它使它更容易以防止這種情況。 – Invictus

+0

它確實有一個左括號,你是否在移動設備上查看這個?我很好,我的代碼是非常可讀的。但我想它的個人喜好。將複查。 – crushman

+0

我正在閱讀這通過正常的SO界面。我沒有在那裏看到右大括號,'mdatabase.open();'後面跟着'Cursor cCompare = mdatabase.getAllItems();'。另外,我看到'else else {'這樣的行難於閱讀,如果你在「else」附近加了空格,那麼else語句中的Log.d()調用甚至沒有縮進。我不太確定爲什麼你對使用垂直空間似乎非常謹慎 - 我會推薦'else'至少在與前面if語句的結束括號分開的一行中,我自己。 – Invictus

回答

0

compareLocations()每次調用將條目添加一些closelist。它不斷增長並不斷增長,並且for循環從不終止。

你可能想

  • 電話compareLocations()只有一次,從一個新的開始緩存結果

  • 構建closeList每次調用compareLocations(),而不是追加到現有的一些列表

+0

將我的closeList數組放入我的compareLocations函數中。謝謝 – crushman