简体   繁体   中英

Can't get address from longitude and latitude in android

I am trying to get my address from longitude and latitude , but when I am trying to do so , it doesn't work . It says W/System.err﹕ at teamtreehouse.com.stromy.MainActivity.getCompleteAddressString(MainActivity.java:163) in logcat

Here is the method I have tried

private   String getCompleteAddressString() {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            //     Log.w("My Current loction address", "" + strReturnedAddress.toString());

        } else {
            //    Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        //  Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}

And I call it like

public void updateDisplay() {
    mLocation.setText(getCompleteAddressString());
}

In getCompleteAddressString() method , I have used longitude and latitude , which I have already got from a another method and it is working fine . Both method are running withing main activity . All other things are working fine except this , how can I solve it ? what are reason of this error ?

Try like this way:

        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        Address addr = null;
        try {
            addresses = gcd.getFromLocation(latitude, longitude, 1);
            if (addresses != null && addresses.size() > 0) {
                addr = addresses.get(0);
                String info = "Address is:  ";
                info += addr.getMaxAddressLineIndex() > 0 ? addr
                        .getAddressLine(0) : "";
                info = info + ", " + addr.getLocality() + ", "
                        + addr.getCountryName();
                Toast.makeText(getApplicationContext(), info,
                        Toast.LENGTH_LONG).show();
            } else
                Toast.makeText(getApplicationContext(),
                        "Address not found", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Address not found",
                    Toast.LENGTH_LONG).show();
        }

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