6

I am going out of my mind for the last two days with an IllegalArgumentException error I receive in Android code when trying to get a coordinates out of an address, or even reverse, get address out of longitude and latitude. This is the code, but I cannot see an error. It is a standard code snippet that is easily found on a Google search.

public GeoPoint determineLatLngFromAddress(Context appContext, String strAddress) {
    Geocoder geocoder = new Geocoder(appContext, Locale.getDefault());
    GeoPoint g = null; 
    try {
        System.out.println("str addres: " + strAddress);
        List<Address> addresses = geocoder.getFromLocationName(strAddress, 5);
        if (addresses.size() > 0) {
            g = new GeoPoint(
               (int) (addresses.get(0).getLatitude() * 1E6),
               (int) (addresses.get(0).getLongitude() * 1E6)
            );
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("locationName == null");
    }
    return g;
 }

These are the permissions from manifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

I do have the Google API key declared too: <uses-library android:name="com.google.android.maps" />

From the code snippet above, geocoder is not null, neither is the address or appContext, and I stumble here: geocoder.getFromLocationName(strAddress, 5);

I did a lot of Google searching and found nothing that worked, and the most important info I found is this:

The Geocoder class requires a backend service that is not included in the core android framework.

Sooo, I am confuzed now. What do I have to call, import, add, use in code.... to make this work? I am using Google API 2.2, API level 8. If somebody has found a solution for this, or a pointer for documentation, something that I didn't discover, please let us know.

JJD
  • 50,076
  • 60
  • 203
  • 339
test
  • 105
  • 1
  • 2
  • 6

4 Answers4

14

I had a similar problem and found that polling the Geocoder until i got a result worked. Here is how i did it, so far works great.

try {
    List<Address> geoResults = geocoder.getFromLocationName("<address goes here>", 1);
    while (geoResults.size()==0) {
        geoResults = geocoder.getFromLocationName("<address goes here>", 1);
    }
    if (geoResults.size()>0) {
        Address addr = geoResults.get(0);
        myLocation.setLatitude(addr.getLatitude());
        myLocation.setLongitude(addr.getLongitude());
    }
} catch (Exception e) {
    System.out.print(e.getMessage());
}
pmko
  • 5,071
  • 3
  • 23
  • 25
  • 1
    i was able to fix it. i had force closed the Android maps App..once i restarted the emulator. it worked fine – i_raqz Mar 15 '11 at 05:31
  • Good solution - I set a threshold of 10 attempts just so it doesn't get into an endless loop. If all else fails I then used the Maps API: https://developers.google.com/maps/documentation/geocoding/ – bkurzius Oct 02 '12 at 21:20
  • Hay @chris, your code is working exactly fine...I am passing address from SearchView on my actionBar to this method that u mentioned above. What i wonder is how can i show suggestions fro address right under the searchbar as google does. – Ali Ansari Nov 13 '14 at 11:12
  • I tried the above solution and many exceptions occurred. Is there any way that you could give me some help, if i post a new question ? – Marialena Feb 22 '15 at 21:03
  • @AliAnsari if you have not got your solution still then check these links : 1. http://developer.android.com/reference/android/widget/AutoCompleteTextView.html 2.https://developers.google.com/places/android-api/ – Saurabh Jain Sep 02 '15 at 14:10
2
public LatLng determineLatLngFromAddress(Context appContext, String strAddress) {
        LatLng latLng = null;
        Geocoder geocoder = new Geocoder(appContext, Locale.getDefault());
        List<Address> geoResults = null;

        try {
            geoResults = geocoder.getFromLocationName(strAddress, 1);
            while (geoResults.size()==0) {
                geoResults = geocoder.getFromLocationName(strAddress, 1);
            }
            if (geoResults.size()>0) {
                Address addr = geoResults.get(0);
                latLng = new LatLng(addr.getLatitude(),addr.getLongitude());
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }

    return latLng; //LatLng value of address
    }
mahbub_siddique
  • 1,755
  • 18
  • 22
2

Had the same problem. Pooling didn't work so I used this to get the location: Geocoding Responses

Use this class to get JSONObject of location:

public class GetLocationDownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {


        String result = "";
        URL url;
        HttpURLConnection urlConnection;
        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream is = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(is);

            int data = inputStreamReader.read();
            while(data != -1){
                char curr = (char) data;
                result += curr;
                data = inputStreamReader.read();
            }
            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result != null) {
            try {
                JSONObject locationObject = new JSONObject(result);
                JSONObject locationGeo = locationObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");


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

    }

You can create and run the class instance like this:

String link = "https://maps.googleapis.com/maps/api/geocode/json?address=" + addressString + "&key={YOUR_API_KEY}";

GetLocationDownloadTask getLocation = new GetLocationDownloadTask();

getLocation.execute(link);
Filip
  • 53
  • 7
0

Run your code on Android 2.0, It will work. I had the same problem with may code. Its not working in 2.2, don't know why

Sandy
  • 6,285
  • 15
  • 65
  • 93
  • I will try it with Android2.0, thank you.Hopefully it will work, if so, will let you know. Happy New Year! – test Dec 31 '10 at 10:33