get current location city name, android

android, location

Solution

 public String getLocationName(double lattitude, double longitude) {

    String cityName = "Not Found";
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
    try {

        List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                10);

        for (Address adrs : addresses) {
            if (adrs != null) {

                String city = adrs.getLocality();
                if (city != null && !city.equals("")) {
                    cityName = city;
                    System.out.println("city ::  " + cityName);
                } else {

                }
                // // you should also try with addresses.get(0).toSring();

            }

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

}

Problem

I am writing an android application to get current location city name, I get the latitude and longitude right, but I can't get the city name. here is my code : ``` // To get City-Name from coordinates String cityName = null; Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); List<Address> addresses = null; try { addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); if (addresses.size() > 0) System.out.println(addresses.get(0).getLocality()); cityName = addresses.get(0).getLocality(); } catch (IOException e) { e.printStackTrace(); } String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: " + cityName; editLocation.setText(s); ```

Original source