Search code examples
androidgeocode

Error:(28, 58) error: incompatible types: Object cannot be converted to Address


I am creating an app which would display latitutes and longitudes from a given string

Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
  List addressList = geocoder.getFromLocationName(locationAddress, 1);
  if (addressList != null && addressList.size() > 0) {
     Address address = addressList.get(0);
     StringBuilder sb = new StringBuilder();
     sb.append(address.getLatitude()).append("\n");
     sb.append(address.getLongitude()).append("\n");
     result = sb.toString();
  }
}

and this exception is occuring:

Error:(28, 58) error: incompatible types: Object cannot be converted to Address
The List addressList is storing address type values .

Solution

  • This is because you use a raw type, which is List. You need to use List<Address>.

    When the following code is called:

    Address address = addressList.get(0);
    

    It returns an Object from the following code:

    List addressList = geocoder.getFromLocationName(locationAddress, 1);
    

    Then it will give an error because addressList.get(0) is an Object which isn't an instanceof Address.

    Read more about raw type: https://stackoverflow.com/a/2770692/4758255