2014-04-29 2 views
0

저는 Android에서 매우 새로운데 도시에서 좌표를 검색하려고합니다. 아래의 코드를 다양한 자습서에 따라 작성했습니다. 그것의 문제는 행을 실행 한 후 "HttpResponse response = client.execute (request);" 그것은 exceptio에 직접적으로 뛰어 오르고 정말 이유를 이해할 수 없습니다. 나는 지난 이틀 동안 이걸로 힘들게 지내왔다. 내가 매니페스트 파일 및 프로젝트 빌드 대상에 추가 한좌표 검색을 시도하는 중 HttpResponse를 사용하는 중에 예외가 발생했습니다.

안드로이드 사물의 이러한 종류의 작업을 수행하는 지오 코더의 빌드를 가지고 구글 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; 

} 
+0

당신은 스레드 나 AsyncTask를의 코드를 실행하고 있습니까? 그렇지 않으면 주 스레드에서 인터넷 작업을 수행하려고 시도하는 것에 대해 불평 할 것입니다 (UI 고정을 만들 수 있음). – cYrixmorten

+0

아니요, 저는 아닙니다 ... 스레드 또는 AsyncTask에 대해 처음 들었습니다. 그 중 하나에서 코드를 실행하는 것이 좋습니다. 많은 감사 – EvaBT9

답변

0

입니다. 하지만 때로는 실패하고 HTTP로 폴백하는 것이 좋습니다.

이 질문에 대한 답변 : Google Geocoder service is unavaliable (Coordinates to address) AsyncTask에서 둘 모두를 사용하여 구현을 추가했습니다.

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

을 그리고 onPostExcecute에서 결과 처리 :

는이 기능을 사용하려면 다른 곳에서 답을 운송 활성화하려면

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

, 당신은 GetAddressPositionTask을 콜백 인터페이스를 추가하거나 추가 할 필요를 내부 클래스로서, 응답이 준비되었을 때 외부 클래스의 메서드를 호출 할 수 있습니다. 완성도를 들어

나도 여기 GetAddressPositionTask에 대한 코드를 추가

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

}; 
+0

많은 많은 감사합니다 !! GeoCoder에 대한 아이디어가 없습니다. 나는이 코드를 시도 할 것이고, 그것이 효과가 있기를 희망한다! – EvaBT9

+0

문제 없음 :) 지금 당장 앱에서 사용하고 있으므로 제대로 작동합니다. – cYrixmorten

+0

예, 완전히 맞습니다! 완벽하게 작동합니다! :디 – EvaBT9

관련 문제