1

I'm trying to reverse geocode, using htc desire c, when running the app, its throwing service not available exception. But GeoCoder.isPresent() is returning 'true'. Please help me out in finding the issue.

This is my code:

public class MainActivity extends Activity {

LocationManager lManager;
String provider;
 Location location ;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    provider = lManager.getBestProvider(criteria, false);
    if(provider!=null && !provider.equals("")){

        // Get the location from the given provider
      location = lManager.getLastKnownLocation(provider);
    }

    boolean geoCoder = false;
    Geocoder geo = new Geocoder(this, Locale.getDefault());
     geoCoder = Geocoder.isPresent();
     System.out.println("GEO CODER : "+geoCoder);

     try {
        List<Address> address = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 3);
        System.out.println("Size------------- "+address.size());

        /*Address addr = address.get(0);
        System.out.println("City "+addr.getLocality());*/
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("in here--------------");
        e.printStackTrace();
    }

}

Log:

03-16 10:33:58.609: I/System.out(30398): GEO CODER : true
03-16 10:33:58.609: I/System.out(30398): in here--------------
03-16 10:33:58.609: W/System.err(30398): java.io.IOException: Service not Available
03-16 10:33:58.619: W/System.err(30398):    at  android.location.Geocoder.getFromLocation(Geocoder.java:136)
03-16 10:33:58.619: W/System.err(30398):    at   com.example.geocoder.MainActivity.onCreate(MainActivity.java:46)
03-16 10:33:58.619: W/System.err(30398):    at   android.app.Activity.performCreate(Activity.java:4538)
03-16 10:33:58.629: W/System.err(30398):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
03-16 10:33:58.629: W/System.err(30398):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
03-16 10:33:58.629: W/System.err(30398):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
03-16 10:33:58.629: W/System.err(30398):    at android.app.ActivityThread.access$600(ActivityThread.java:139)
03-16 10:33:58.629: W/System.err(30398):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
03-16 10:33:58.629: W/System.err(30398):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 10:33:58.629: W/System.err(30398):    at android.os.Looper.loop(Looper.java:156)
03-16 10:33:58.629: W/System.err(30398):    at android.app.ActivityThread.main(ActivityThread.java:4987)
03-16 10:33:58.639: W/System.err(30398):    at java.lang.reflect.Method.invokeNative(Native Method)
03-16 10:33:58.639: W/System.err(30398):    at java.lang.reflect.Method.invoke(Method.java:511)
03-16 10:33:58.639: W/System.err(30398):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-16 10:33:58.639: W/System.err(30398):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-16 10:33:58.649: W/System.err(30398):    at dalvik.system.NativeStart.main(Native Method)
Anil M
  • 1,297
  • 2
  • 19
  • 42

1 Answers1

1

@smk gave you a useful link. To save you from a lot of research I'll try to answer you in short. Geocoder doesn't always return a value. You can try to send a request 3 times in a for loop. I should be able to return atleast once. If not then, their might be a connection issue or can be other issues like server does not reply to your request.

I had a while loop as well but I used to try it maximum for 10 times. Sometimes, it never returned anything even if it was connected to internet. Then, I used this much more reliable way to get the address everytime:

I used to get the latitude and longitude and then request google servers, to reply with a JSOn object containing various information about the location co-ordinates. Here is the function:

public JSONObject getLocationInfo() {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&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 {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

I called it as follows:

JSONObject ret = getLocationInfo(); 
JSONObject location;
String location_string;
try {
    location = ret.getJSONArray("results").getJSONObject(0);
    location_string = location.getString("formatted_address");
    Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
    e1.printStackTrace();

}

Hope this helps. I was also tired of relying on Geocoder. This worked for me. Though it might be slower than geocoder. You can just replace in the URL with the lat and longitude coordinates you are having. Try to see the returned JSON object in a web browser. You'll see how you can extract the address string. Try and read these threads as well:

Geocoder doesn't always return a value and geocoder.getFromLocationName returns only null

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • Thanks for the answer Shobhit Puri!! I was really struck usign GeoCoder...will try to implement your answer :) – Anil M Mar 16 '13 at 05:30
  • No problem. I was stuck in it for a day as well. SO just thought a little heads up would be good. All the best. Also, if you find any better solution for the Geocoer problem, please do post it. :) – Shobhit Puri Mar 16 '13 at 05:34
  • sure I would post if I find any better solution :) – Anil M Mar 16 '13 at 05:40
  • Hi Shobhit, I was able to retrieve location successfully , but [this](https://developers.google.com/maps/documentation/geocoding/index) says that the url has to be used only if we implement google maps? – Anil M Mar 18 '13 at 05:27
  • As I said, it takes a bit of time to get the location. It is a kind of alternative to get the address String. Everything has its pros and cons. – Shobhit Puri Mar 18 '13 at 07:10
  • No, what I'm trying to say is, the url should be used only if we implement google maps in our app and not as standalone..this is note present in the link: **Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. For complete details on allowed usage, consult the Maps API Terms of Service License Restrictions.** – Anil M Mar 18 '13 at 07:28
  • Thanks for pointing it out. I missed the 'legal' part. I am using Google Maps in the App that I am working upon. As it says legally you should not use it (and don't) but conceptually you can. – Shobhit Puri Mar 18 '13 at 07:32
  • hmmm..so I need to look for an alternative or try to use maps some where in the app :) – Anil M Mar 18 '13 at 07:39