2015-11-04 19 views
1

當我按國家名搜索時,它工作得很完美,但是當我搜索城市或地點時,應用程序崩潰。下面是代碼:當我搜索城市(或任何其他國家名稱)時,Android中的地理位置投擲異常

EditText location_tf = (EditText)findViewById(R.id.TFaddress); 
     String location = location_tf.getText().toString(); 
     //Toast.makeText(this, location, Toast.LENGTH_SHORT).show(); 

     Geocoder gc = new Geocoder(this); 
     List<Address> list = gc.getFromLocationName(location, 1); 
     Address add = list.get(0); 
     String locality = add.getLocality(); 
     Toast.makeText(this, locality, Toast.LENGTH_SHORT).show(); 

     double lat = add.getLatitude(); 
     double lng = add.getLongitude(); 

     gotoLocation(lat, lng, 4); 
+0

發佈您的問題的異常跟蹤 –

回答

1

感謝您的幫助,我發現你的回答可以幫助的東西。 我的問題解決了,我在MIUI中文ROM上測試應用程序,安裝MIUI國際ROM後,我的代碼像魅力一樣工作。

謝謝。

0

要在任何城市或國家的細節只是使用定義here的API。該API基本上是 - http://maps.googleapis.com/maps/api/geocode/json?address=<yourCityName>&sensor=false

1

基礎上提供了這個問題的答案SO線程

我會說, Geocoder並不總是返回一個值。您需要嘗試在for循環中發送3次請求。我應該能夠返回至少一次。如果不是那麼,他們可能是一個連接問題,也可能是其他問題,如服務器無法回覆您的請求。

你需要嘗試像下面

try { 
    List<Address> geoResults = geocoder.getFromLocationName("<address goes here>", 1); 
    while (geoResults.size()==0) { 
     geoResults = geocoder.getFromLocationName("<address goes here>", 1); 
    } 
    if (geoResults.size()>0) { 
     Address addr = geoResults.get(0); 
     myLocation.setLatitude(addr.getLatitude()); 
     myLocation.setLongitude(addr.getLongitude()); 
    } 
} catch (Exception e) { 
    System.out.print(e.getMessage()); 
} 
相關問題