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

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

我正在创建一个可以显示给定字符串的纬度和经度的应用程序

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();
  }
}

并且发生了这个异常:

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

这是因为您使用了原始类型,即 List。您需要使用 List<Address>.

调用以下代码时:

Address address = addressList.get(0);

它 returns 来自以下代码的 Object

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

然后它会给出一个错误,因为 addressList.get(0) 是一个对象,它不是 instanceof 地址。

阅读有关原始类型的更多信息: