0

I'm quite new on Android and I am trying to search the coordinates from a city. I have made the code below following various tutorials. The problem on it is that after executed the row "HttpResponse response = client.execute(request);" it jumps directly to the exceptio and really can't understand why. I've been struggeling with this for the past two days.

I have add in the manifest file and the project build target is Google API 4.2.2

public double[] searchCoordinate(String city) {

   double[] coordinates = new double[2];
   String petHTTP1 = "http://maps.googleapis.com/maps/api/geocode/json?address=";
   String petHTTP2 = "&sensor=false";
   String petHTTP = petHTTP1 + city + petHTTP2;

   try {

      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet();
      request.setURI(new URI(petHTTP));
      HttpResponse response = client.execute(request);
      BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      StringBuffer sb = new StringBuffer("");
      String line = "";
      while ((line = in.readLine()) != null){
          sb.append(line);
      }
      in.close();

      System.out.println(sb.toString());

      JSONObject jsonObject = new JSONObject(sb.toString());
      String resp = jsonObject.getString("status");
      if (resp.equals("OK")) {
          JSONArray array = jsonObject.getJSONArray("results");
          JSONObject item = array.getJSONObject(0);
          JSONObject point = item.getJSONObject("geometry").getJSONObject("location");
          coordinates[0] = point.getDouble("lat");
          coordinates[1] = point.getDouble("lng");
          System.out.println("Longitude: "+coordinates[0]+" - Latitude: "+coordinates[1]);

      } 

  }catch (Exception e)  {
      e.printStackTrace();      
  }

  return coordinates;

} 
EvaBT9
  • 3
  • 1
  • Are you running the code in a Thread or AsyncTask? Otherwise it will complain about trying to perform an internet operation on main thread (which could make UI freeze). – cYrixmorten Apr 29 '14 at 16:28
  • No, I am not... It's the first time I heard about Thread or AsyncTask. Are you suggesting then that I shoud run the code in one of both? Many thanks – EvaBT9 Apr 29 '14 at 16:35

1 Answers1

0

Android has a build in GeoCoder to do these sorts of things. Though, sometimes it fails and it makes sense to fallback to HTTP.

In my answer to this question: Google Geocoder service is unavaliable (Coordinates to address) I have added an implementation using both in an AsyncTask.

To use it:

new GetAddressPositionTask().excecute("someaddress");

And then handle the result in onPostExcecute:

@Override
protected void onPostExecute(LatLng result) {
    // use the looked up location here
    super.onPostExecute(result);
}

To enable shipping off the answer elsewhere, you need to add a callback interface, or simply add GetAddressPositionTask as an inner class, which makes it possible to call a method of the outer class when the answer is ready.

For completeness I add the code for GetAddressPositionTask here too:

private class GetAddressPositionTask extends
        AsyncTask<String, Integer, LatLng> {

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

    @Override
    protected LatLng doInBackground(String... plookupString) {

        String lookupString = plookupString[0];
        final String lookupStringUriencoded = Uri.encode(lookupString);
        LatLng position = null;

        // best effort zoom
        try {
            if (geocoder != null) {
                List<Address> addresses = geocoder.getFromLocationName(
                        lookupString, 1);
                if (addresses != null && !addresses.isEmpty()) {
                    Address first_address = addresses.get(0);
                    position = new LatLng(first_address.getLatitude(),
                            first_address.getLongitude());
                }
            } else {
                Log.e(TAG, "geocoder was null, is the module loaded? "
                        + isLoaded);
            }

        } catch (IOException e) {
            Log.e(TAG, "geocoder failed, moving on to HTTP");
        }
        // try HTTP lookup to the maps API
        if (position == null) {
            HttpGet httpGet = new HttpGet(
                    "http://maps.google.com/maps/api/geocode/json?address="
                            + lookupStringUriencoded + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                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 {
                // Log.d("MAPSAPI", stringBuilder.toString());

                jsonObject = new JSONObject(stringBuilder.toString());
                if (jsonObject.getString("status").equals("OK")) {
                    jsonObject = jsonObject.getJSONArray("results")
                            .getJSONObject(0);
                    jsonObject = jsonObject.getJSONObject("geometry");
                    jsonObject = jsonObject.getJSONObject("location");
                    String lat = jsonObject.getString("lat");
                    String lng = jsonObject.getString("lng");

                    // Log.d("MAPSAPI", "latlng " + lat + ", "
                    // + lng);

                    position = new LatLng(Double.valueOf(lat),
                            Double.valueOf(lng));
                }

            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
            }

        }
        return position;
    }

    @Override
    protected void onPostExecute(LatLng result) {
        super.onPostExecute(result);
    }

};
Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33