15

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.

rayman
  • 20,786
  • 45
  • 148
  • 246

7 Answers7

21

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.

ddewaele
  • 22,363
  • 10
  • 69
  • 82
  • I have managed to do it with Emulator 2.1 and API7, but the reverse coding code always return empty results, any idea why? – rayman Mar 06 '11 at 09:20
  • rayman : I've updated the answser ... are you getting an exception when performing the Geocoder lookup ? – ddewaele Mar 06 '11 at 10:55
  • Nope, just en empty result in the list addresses( List
    addresses)
    – rayman Mar 06 '11 at 12:24
  • Ah ok ... check the updated answer... Check if an implementation is present and if your AVD is setup with the Google APIs. – ddewaele Mar 06 '11 at 13:25
  • Yes.. it is setup with Google apis.. and I get Unable to parse response from server – rayman Mar 07 '11 at 15:54
  • @ddewaele : As the [Geocoder](http://developer.android.com/reference/android/location/Geocoder.html#isPresent()) documentation says `Geocoder.isPresent()` "returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented." It doesn't mean you can use them successfully. When I test my application on an AVD 2.3.3 I get `java.io.IOException: Service not Available` while `Geocoder.isPresent()` return true. – a.b.d Apr 08 '12 at 16:09
10

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..

Reno
  • 33,594
  • 11
  • 89
  • 102
a4ankur
  • 101
  • 1
  • 2
  • 6
  • Its not working in my case in Android 2.3.3, it just showing the same error i.e. Couldn't get connection factory client. – Harpreet Mar 06 '12 at 11:45
  • this works fine for all google api 7,8,10 i will test on all...Haps ur wrong on somthings...just post ur code... – a4ankur Mar 14 '12 at 13:46
  • It worked for me too. Earlier I was messing with KML parsing and its a headache. But this one is really nice and simple solution. Cheers to GMaps.. – YuDroid Jun 21 '12 at 10:31
  • I keep getting an UnknownHostException. I've done the following: 1> INTERNET Permission has been added AT THE RIGHT PLACE 2> I've checked the internet connection by using the Emulator Browser 3> I recheck the code too! It throws an exception at "response = client.execute(httppost);" – Axe Oct 15 '12 at 03:56
  • 1
    Thanks for the code. But one question: Why use HTTP POST request, it's clearly a HTTP GET with some query parameters. – AndyB Mar 18 '15 at 15:12
4

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.

bjc
  • 103
  • 2
  • thanks a ton and yes it did....seriously a reboot solved !!!!..I was searching a whole day with my code, internet permission etc ....finally this one made my day but still i didn't get the reason.how? – Asif Sb Jan 15 '16 at 06:16
2

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

        }
Rajesh Narwal
  • 898
  • 8
  • 8
1

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

}

0
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
}
41 72 6c
  • 1,600
  • 5
  • 19
  • 30
0

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!

Reno
  • 33,594
  • 11
  • 89
  • 102
Santosh Kumar
  • 189
  • 1
  • 9