1

I have been given a task to find the driving distance between two latitude and longitude coordinates. I have found this link [here][1] however, I'm not sure if I'm implementing it correctly as I'm getting an error....

Invalid float: ""

GeocodingLocation.java

public class GeocodingLocation {

    private static final String TAG = "GeocodingLocation";

    public static void getAddressFromLocation(final String locationAddress,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String endPosition = null;
                try {
                    List
                            addressList = geocoder.getFromLocationName(locationAddress, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = (Address) addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        sb.append(address.getLatitude()).append("\n,");
                        sb.append(address.getLongitude()).append("\n");
                        endPosition = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable to connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (endPosition != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        endPosition = endPosition;
                        bundle.putString("address", endPosition);
                        message.setData(bundle);
                    }
                    else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        endPosition = "Address: " + locationAddress +
                                "\n Unable to get Latitude and Longitude for this address location.";
                        bundle.putString("address", endPosition);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}

Button On Click

public void onClick_btnLocate(View v){
    try {
        String address = tbStreet.getText().toString() + " "
                + tbCity.getText().toString() + " "
                + spinStates.getSelectedItem().toString() + " "
                + tbZip.getText().toString();


        GeocodingLocation locationAddress = new GeocodingLocation();
        locationAddress.getAddressFromLocation(address,
                getApplicationContext(), new GeocoderHandler());


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Handler

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String locationAddress;

        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                locationAddress = bundle.getString("address");
                break;
            default:
               locationAddress = null;
        }


        String splitLocation[] = locationAddress.split(",");
        Float lat2 = Float.parseFloat(splitLocation[0]);
        Float lon2 = Float.parseFloat(splitLocation[1]);
        Float lat1 = Float.parseFloat("39.055564880371094");
        Float lon1 = Float.parseFloat("-84.65643310546875");
        LatLng latLngDest = new LatLng(lat2, lon2);
        LatLng latLngStart = new LatLng(39.055564880371094, -84.65643310546875);

        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLngDest, 10);
        map.addMarker(new MarkerOptions().position(latLngStart).title("Begin Here"));
        map.addMarker(new MarkerOptions().position(latLngDest).title("Take Me Here!"));
        map.animateCamera(update);
        tvLongitude.setText(latLngDest.toString());

        getDistance(lat1, lon1, lat2, lon2);

    }
}

getDistance

public float getDistance(float lat1, float lon1, float lat2, float lon2) {
     String result_in_kms = "";
     String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
     String tag[] = {"text"};
     HttpResponse response = null;
     try {
          HttpClient httpClient = new DefaultHttpClient();
          HttpContext localContext = new BasicHttpContext();
          HttpPost httpPost = new HttpPost(url);
          response = httpClient.execute(httpPost, localContext);
          InputStream is = response.getEntity().getContent();
          DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
          Document doc = builder.parse(is);
          if (doc != null) {
              NodeList nl;
              ArrayList args = new ArrayList();
              for (String s : tag) {
                  nl = doc.getElementsByTagName(s);
                  if (nl.getLength() > 0) {
                      Node node = nl.item(nl.getLength() - 1);
                      args.add(node.getTextContent());
                  } else {
                      args.add(" - ");
                  }
              }
              result_in_kms =String.valueOf( args.get(0));
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
      Float f=Float.valueOf(result_in_kms); //error occurs here, lat lngs are never passed?

      tvLatitude.setText(f.toString()); 

      return f*1000;

  }

Any help is greatly appreciated!

Logcat

01-17 10:05:49.606  29336-29336/com.magtek.mobile.android.scra.MagTekDemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.magtek.mobile.android.scra.MagTekDemo, PID: 29336
    java.lang.NumberFormatException: Invalid float: ""
            at java.lang.StringToReal.invalidReal(StringToReal.java:63)
            at java.lang.StringToReal.parseFloat(StringToReal.java:308)
            at java.lang.Float.parseFloat(Float.java:306)
            at java.lang.Float.valueOf(Float.java:343)
            at com.magtek.mobile.android.scra.MagTekDemo.SelectZone.getDistance(SelectZone.java:164)
            at com.magtek.mobile.android.scra.MagTekDemo.SelectZone$GeocoderHandler.handleMessage(SelectZone.java:129)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

  [1]: http://stackoverflow.com/questions/22609087/how-to-find-distance-by-road-between-2-geo-points-in-android-application-witho
Lal
  • 14,726
  • 4
  • 45
  • 70
Humpy
  • 2,004
  • 2
  • 22
  • 45

1 Answers1

0

Is it possible that your locationAddress is empty such that your parseFloat call has an empty string argument in Handler, or your Float.valueOf argument is empty in getDistance?

EDIT You have now added a stack trace to your question. That clearly points at the Float.valueOf argument in getDistance.

Always test your inputs to methods like valueOf, parseInt etc. for null, empty or invalid strings - that way you can avoid the exceptions that would be thrown. One way to do this is:

if (input != null && input.length() > 0) { ... }

One other problem you are going to have is that in Handler your default switch case sets locationAddress = null;. When you call String splitLocation[] = locationAddress.split(","); it will give you a NullPointerException

Andy Brown
  • 18,961
  • 3
  • 52
  • 62
  • I believe the Float.valueOf argument is empty in getDistance. I display latLngDest in a TextView, which I get from locationAddress so I know that isn't empty. – Humpy Jan 17 '15 at 15:27
  • I see that you have now added a stack trace output to your question - that clearly points at getDistance – Andy Brown Jan 17 '15 at 15:27
  • Yes it does. I'm just not sure how to fix this issue. – Humpy Jan 17 '15 at 15:48