I had exactly the same problem in my app and ended up writing my own GeocodeTask:
class GoogleApiGeocodingTask extends AsyncTask<Location, Void, JSONObject>{
Locale defaultLoc = Locale.getDefault();
GoogleApiGeocodingTask() {}
@Override
protected JSONObject doInBackground( Location... params ) {
try{
Location loc = params[ 0 ]
ResponseTuple rt = doGet( "http://maps.google.com/maps/api/geocode/json?sensor=true&latLng=" + loc.getLattitude() + ',' + loc.getLongitude() + "&language=" + defaultLoc.getLanguage() );
if( 200 == rt.getStatusCode() ) return rt.getJson();
}catch( Exception e ){
Log.e( "DelayedGeocodeHandler", "", e );
}
return null;
}
@Override
protected void onPostExecute( JSONObject json ) {
if( null == json || !"OK".equals( json.optString( "status" ) ) ) return;
try{
JSONArray array = json.getJSONArray( "results" );
for( int ix = 0; ix < array.length(); ix++ ){
JSONObject obj = array.optJSONObject( ix );
JSONObject loc = obj.getJSONObject( "geometry" ).getJSONObject( "location" );
JSONArray components = obj.getJSONArray( "address_components" );
String country = null, city = null;
for( int ixx = 0; ixx < components.length(); ixx++ ){
JSONObject comp = (JSONObject)components.get( ixx );
doSomethingWithAddressComponent( comp );
}
}
}catch( Exception e ){
Log.e( "GoogleApiGeocodingTask", "", e );
}
}
}
Util
and ResponseTuple
are my internal classes and I think, it's pretty obvious what they do
UPDATE:
the missing methods:
public ResponseTuple doGet( String url) throws Exception {
HttpClient httpClient = getHttpClient();
HttpConnectionParams.setConnectionTimeout( httpClient.getParams(), timeout );
HttpGet httpget = new HttpGet( url );
HttpResponse hr = httpClient.execute( httpget );
return new ResponseTuple( hr.getStatusLine().getStatusCode(), asString( hr ) );
}
public static String asString( HttpResponse response ) throws Exception {
BufferedReader reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
try{
StringBuilder sb = new StringBuilder();
String line = null;
while( null != ( line = reader.readLine() ) ) sb.append( line );
return sb.toString().trim();
}finally{
reader.close();
}
}
and the class:
public class ResponseTuple {
private int statusCode;
private String body;
public ResponseTuple( int statusCode, String body ) {
this.statusCode = statusCode;
this.body = body;
}
public int getStatusCode() {
return statusCode;
}
public String getBody() {
return body;
}
public JSONObject getJson() throws JSONException {
return new JSONObject( body );
}
}
Also I saw, that you need a reverse
geocodig, so I adopted the URL appropriately