android - 构造函数 Geocoder() 未定义

标签 android

我一直在使用以下代码获取未定义的 Geocoder。我试图简单地从纬度和经度中获取一个地方的地址。 Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); 这一行总是以未定义的形式返回。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /* Use the LocationManager class to obtain GPS locations */
    LocationManager mlocManager =
    (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new MyLocationListener();
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 600000, 1000, mlocListener);

/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
currentLatitude = loc.getLatitude();
currentLongitude = loc.getLongitude();

try {
      List<Address> addresses = geocoder.getFromLocation(currentLatitude, currentLongitude, 1);

      if(addresses != null) {
       Address returnedAddress = addresses.get(0);
       StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
       for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
       }
       myAddress.setText(strReturnedAddress.toString());
      }
      else{
       myAddress.setText("No Address returned!");
      }
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      myAddress.setText("Canont get Address!");
     }

最佳答案

那是因为它是未定义的:http://developer.android.com/reference/android/location/Geocoder.html向您展示了 2 个构造函数。一个采用 Context,另一个采用 Context 和 Locale,但关键是您是在 MyLocationListener 类中创建它。尝试使用这个:

Geocoder geocoder = new Geocoder(<ACTIVITY CLASS NAME>.this, Locale.ENGLISH);

相反。

出于性能原因,您可能希望在 MyLocationListener 类的构造函数中创建 Geocoder 的单个实例,而不是每次获取位置时都生成一个实例更新。

关于android - 构造函数 Geocoder() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5836033/

相关文章:

android - 在带有图像的 ListView 中延迟加载。 (游标适配器)

android 私有(private)聊天自动刷新

android - 为什么我在运行 `NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling` 时得到 `./gradlew tasks` ?

java - Intent-Filter 要么允许通过 URL 启动,要么允许应用出现在 Android 启动器中

android - 如何从数组列表中隐藏 2 个不正确的答案并启用 2 个可能的答案?

java - 如何在 java 7 (android) 中并行化嵌套循环

java - 如何在单击按钮时将数据写入特征?

android - 使用 rxjava2 时出现 Retrofit2 Unauthenticated 401 错误

android - 如何在TextView中显示带有css样式表的html?

android - 从 Android 照片库中获取所有图像