简体   繁体   中英

Geocoder.getFromLocation throws IOException on Android emulator

Using Android emulator 2.2 api 8 I keep getting IOException

03-05 19:42:11.073: DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
03-05 19:42:15.505: WARN/System.err(1823): java.io.IOException: Service not Available

Thats my code:

private LocationManager manager = null;
LocationListener locationListener = null;
double latitude = 0;
double longtitude = 0;
List<Address> myList = null;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // httpTranslateGet();
    try
    {


        manager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);


        initLocationListener();

        manager.requestLocationUpdates(manager.GPS_PROVIDER, 0, 0,
                locationListener);

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

}

private void initLocationListener()
{
    locationListener = new LocationListener()
    {

        @Override
        public void onLocationChanged(android.location.Location location)
        {
            if (location != null)
            {

                latitude = location.getLatitude();
                longtitude = location.getLongitude();


                try
                {
                    Geocoder geocoder = new Geocoder(WeatherCastDemo.this, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                    myList = geocoder.getFromLocation(
                            location.getLatitude(),
                            location.getLongitude(), 10);

                    StringBuilder sb = new StringBuilder();
                    if (myList.size() > 0)
                    {
                        Address address = myList.get(0);

                        for (int i = 0; i < address
                                .getMaxAddressLineIndex(); i++)
                            sb.append(address.getAddressLine(i)).append(
                                    "\n");

                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());

                    }
                }

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

            }

        }

        @Override
        public void onProviderDisabled(String arg0)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras)
        {

        }
    };
}

anyone has any idea?

I have managed to do it with Emulator 2.1 api 7, but then the reverse geocoding always give an empty result. anyone could confirm my code?

thanks.

thanks, ray.

This is a know issue with the Emulator. It works fine on an actual device

On 2.2 API 8 you'll receive the following stacktrace

java.io.IOException: Service not Available
 at android.location.Geocoder.getFromLocation(Geocoder.java:117)

See here for more info (and a possible workaround) see the following URL :

http://code.google.com/p/android/issues/detail?id=8816

If you're having issues using the GeoCoder on lower APIs you should check the stacktrace. From time to time I'm having the following :

java.io.IOException: Unable to parse response from server
 at android.location.Geocoder.getFromLocation(Geocoder.java:124) 

This can be anything from a server-side issue at Google, or an issue on the client (internet connection).

If the GeoCoder returns an empty list, you need to check if you have a proper GeoCoder implementation available on the device (emulator or real phone).

This can be done using the isPresent() method on the Geocoder object.

http://developer.android.com/reference/android/location/Geocoder.html

Also, when running on an emulator, make sure your AVD image is setup with the Google APIs.

You can use of Google Place API in following way

create a method that returns a JSONObject with the response of the HTTP Call like following

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {

    address = address.replaceAll(" ","%20");    

    HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
    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());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}

now pass that JSONObject to getLatLong() method like following

public static GeoPoint  getLatLong(JSONObject jsonObject) {

        Double lon = new Double(0);
        Double lat = new Double(0);

        try {

            lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

            lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

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

        }

        return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
    }

this is worked and tested...on API level 8...hop this help..

I read the discussion thread mentioned by @ddewaele, someone said that reboot can solve the problem. It did. BTW, the Android version of my device is 4.1.

Latitude and longitute are your respective values

Geocoder geocoder = new Geocoder(getBaseContext(), Locale.ENGLISH);
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);

            if (addresses.size() > 0) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder(
                        "Address:\n");
                for (int i = 0; i < returnedAddress
                        .getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(
                            returnedAddress.getAddressLine(i)).append("\n");
                }
                adrs.setText(strReturnedAddress.toString());
            } else {
                adrs.setText("No Address returned!");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

A little change in the code above, allow to replace getFromLocationName call which seems not supported in some Terminals:

private static List<Address> getAddrByWeb(JSONObject jsonObject){
    List<Address> res = new ArrayList<Address>();
    try
    {
        JSONArray array = (JSONArray) jsonObject.get("results");
        for (int i = 0; i < array.length(); i++)
        {
            Double lon = new Double(0);
            Double lat = new Double(0);
            String name = "";
            try
            {
                lon = array.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

                lat = array.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
                name = array.getJSONObject(i).getString("formatted_address");
                Address addr = new Address(Locale.getDefault());
                addr.setLatitude(lat);
                addr.setLongitude(lon);
                addr.setAddressLine(0, name != null ? name : "");
                res.add(addr);
            }
            catch (JSONException e)
            {
                e.printStackTrace();

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

    }

    return res;
}

}

fun getPostalCode(context: Context, latitude: Double, longitude: Double) : String 
{
    val geocoder = Geocoder(context, Locale.getDefault())
    var postalCode = ""
    try {
        val address = geocoder.getFromLocation(latitude, longitude, 1)

        if (address != null && address[0] != null && address[0].postalCode != null)
            postalCode = address.get(0).postalCode

    }
    catch (e: IOException) {
        Log.e(TAG, e.toString())
    }
    return postalCode
}

You can use the code given by Mr.cyclopes49 as two functions and add function calls to getLatLong() and getLocationInfo() in onCreate() method it works sample statement is

JSONObject jo = this.getLocationInfo("vizianagaram");
GeoPoint p=this.getLatLong(jo);
Toast.makeText(getBaseContext(), 
                        p.getLatitudeE6() / 1E6 + "," + 
                        p.getLongitudeE6() /1E6 , 
                        Toast.LENGTH_SHORT).show();

This works fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM