2016-09-19 20 views
1

我試圖通過有經度和緯度來獲取位置信息(國家名稱,城市名稱等)。但是,以下代碼不返回任何地址,addresses.size()始終爲零!我需要幫助。謝謝。Geocoder.getFromLocation()不返回任何地址

public class FirstUsage extends Activity{ 

private LocationListener myLocListener; 
private LocationManager myLocManager; 
private TextView tv; 
private Button okButt; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.first_use_page); 

    tv = (TextView)findViewById(R.id.TextView_firstPageCoordination); 
    okButt = (Button)findViewById(R.id.firstPageOKButt); 

    myLocManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    setLocationChangeListener(); 
} 

private void setLocationChangeListener() { 
    myLocListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 

      /*----------to get City-Name from coordinates ------------- */ 
      String countryName = null; 
      Geocoder gcd = new Geocoder(FirstUsage.this, Locale.getDefault()); 
      List<Address> addresses; 
      try { 
       addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
       if (addresses.size() > 0) { 

        Address returnedAddress = addresses.get(0); 
        countryName = returnedAddress.getCountryName(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      tv.setText("Your current country is: " + countryName + "\n Your current coordination is:\n" + "Longitude: " + location.getLongitude() + " Latitude: " + location.getLatitude()); 


      ///// 
      if (ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       return; 
      } 
      myLocManager.removeUpdates(myLocListener); 
     } 

回答

1

android documentation

地理編碼器類需要不包括在 Android核心框架的後端服務。

問題是Geocoder後端服務在您的設備/模擬器中不可用。您的設備/模擬器需要Google API才能正確使用Grocoder。

1

有時會在連接不可用或未實現後端時追加。驗證這兩個事情的最好方法是檢查地址解析器存在使用這樣的:

gcd.isPresent() 

返回true如果地理編碼方法getFromLocation和 getFromLocationName實現。缺少網絡連接可能 仍然會導致這些方法返回空列表或空列表。

+0

然後,如果gcd.isPresent()不存在,該怎麼辦? –