0

I want to calculate distance between two locations by road/like driving mode. Here is my code but error is coming at "response = client.execute(httppost);" this line.Please help me.

private double getDistance(double latFrom, double lngFrom,double latTo,double lngTo) {
    StringBuilder stringBuilder = new StringBuilder();
    String apikey="API KEY";
    Double dist = 0.0;
    try {


        String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false"+"&key="+apikey;

        HttpPost httppost = new HttpPost(url);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {

        jsonObject = new JSONObject(stringBuilder.toString());
        JSONArray array = jsonObject.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject distance = steps.getJSONObject("distance");
        Log.i("Distance", distance.toString());
        dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return dist;
}
jyotsna
  • 97
  • 1
  • 9

1 Answers1

1

The solution to your error would be to perform all network operations on a background thread. For example, using AsyncTask or Runnable on a separate thread from the main.

To elaborate more on my answer, your network call would be performed in the doInBackground() method of your AsyncTask.

NEVER perform network operations on the main thread because network calls are blocking operations and would severely hinder your UI responsiveness.

Jarvis
  • 392
  • 1
  • 6