2015-04-05 114 views
0

我想從經度和緯度獲取我的地址,但是當我嘗試這樣做時,它不起作用。它W/System.err的說:在teamtreehouse.com.stromy.MainActivity.getCompleteAddressString(MainActivity.java:163)在logcat的無法從經度和緯度中獲取地址android

這是我曾嘗試

private String getCompleteAddressString() { 
    String strAdd = ""; 
    Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
    try { 
     List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); 
     if (addresses != null) { 
      Address returnedAddress = addresses.get(0); 
      StringBuilder strReturnedAddress = new StringBuilder(""); 

      for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { 
       strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); 
      } 
      strAdd = strReturnedAddress.toString(); 
      //  Log.w("My Current loction address", "" + strReturnedAddress.toString()); 

     } else { 
      // Log.w("My Current loction address", "No Address returned!"); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     // Log.w("My Current loction address", "Canont get Address!"); 
    } 
    return strAdd; 
} 

我調用該方法它像

public void updateDisplay() { 
    mLocation.setText(getCompleteAddressString()); 
} 

在getCompleteAddressString()方法,我已經使用經度和緯度,我已經從其他方法了,它是工作的罰款。兩種方法都以主要活動運行。除此之外,其他所有的工作都很好,我該如何解決它?這個錯誤的原因是什麼?

回答

2

嘗試像這樣:

 Geocoder gcd = new Geocoder(this, Locale.getDefault()); 
     List<Address> addresses = null; 
     Address addr = null; 
     try { 
      addresses = gcd.getFromLocation(latitude, longitude, 1); 
      if (addresses != null && addresses.size() > 0) { 
       addr = addresses.get(0); 
       String info = "Address is: "; 
       info += addr.getMaxAddressLineIndex() > 0 ? addr 
         .getAddressLine(0) : ""; 
       info = info + ", " + addr.getLocality() + ", " 
         + addr.getCountryName(); 
       Toast.makeText(getApplicationContext(), info, 
         Toast.LENGTH_LONG).show(); 
      } else 
       Toast.makeText(getApplicationContext(), 
         "Address not found", Toast.LENGTH_LONG).show(); 
     } catch (Exception e) { 
      Toast.makeText(getApplicationContext(), "Address not found", 
        Toast.LENGTH_LONG).show(); 
     }