2011-04-29 126 views
2

我一直在使用下面的代码将Geocoder定义为undefined。我试图简单地从经纬度得到一个地方的地址。 Geocoder行geocoder = new Geocoder(this,Locale.ENGLISH);总是会回到原来的状态。构造函数Geocoder()未定义

@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!"); 
    } 

回答

1

这是因为它是未定义的:http://developer.android.com/reference/android/location/Geocoder.html向您显示了2个构造函数。一个需要Context,另一个需要Context和Locale,但是最重要的是你要在MyLocationListener类中创建它。试试这个:

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

改为。

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

+0

我还有点困惑,在我的具体情况下,会是什么? – 63alfred 2011-05-01 00:31:19

+0

是的,它运作良好。现在我正在寻找如何在android中读取逗号分隔文件。首先,我必须知道在哪里找到它,以便应用程序可以读取它。我可以将逗号分隔的文件中的数据传输到sting或java文件中的一系列数组,但是必须有一种方法可以将逗号分隔的文件放在那里并读取它。再加上逗号分隔的文件有3000个条目,没有多少位,因为它是文本,但会很多打字。 – 63alfred 2011-05-04 19:04:14