Question

My code is supposed to check whether a LatLng is within 3000 meters of the current LatLng. If it is, the program should put a marker on the map. But for some reason it gets stuck in an infinite for loop.

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"));
                    }
            }
...
}

This is my compareLocations() which compares my latlng with a list of 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;
    }
Was it helpful?

Solution

Each call to compareLocations() adds entries to some closelist. It keeps growing and growing and the for loop never terminates.

You probably want to

  • call compareLocations() only once and cache the result

  • build closeList from a fresh start on each call to compareLocations() instead of appending to some existing list

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top