2012-09-11 65 views
0

在我的應用程序中,我必須查找給定位置是否在指定區域下。我以新德里康樂廣場爲中心點。並且我得到了離中心點200英里以內的地址。但是,如果我輸入任何無效的位置,如「abcdfdfkc」,則應用程序崩潰,因爲它試圖找到此位置的座標,我想避免這種情況。Android:應用程序在輸入無效位置時崩潰

下面我張貼的代碼:

public static boolean isServicedLocation(Context _ctx, String strAddress){ 
    boolean isServicedLocation = false; 

    Address sourceAddress = getAddress(_ctx, "Connaught Place, New Delhi, India"); 
    Location sourceLocation = new Location(""); 
    sourceLocation.setLatitude(sourceAddress.getLatitude()); 
    sourceLocation.setLongitude(sourceAddress.getLongitude());  

    Address targetAddress = getAddress(_ctx, strAddress); 
    Location targetLocation = new Location(""); 

    if (targetLocation != null) { 
     targetLocation.setLatitude(targetAddress.getLatitude()); 
     targetLocation.setLongitude(targetAddress.getLongitude()); 
     float distance = Math.abs(sourceLocation.distanceTo(targetLocation)); 
     double distanceMiles = distance/1609.34; 
     isServicedLocation = distanceMiles <= 200; 

     //Toast.makeText(_ctx, "Distance "+distanceMiles, Toast.LENGTH_LONG).show(); 
    }  

    return isServicedLocation; 
} 

的getAddress方法:

public static Address getAddress(Context _ctx, String addressStr) { 
    Geocoder geoCoder = new Geocoder(_ctx, Locale.getDefault()); 
    try { 
     List<Address> addresses = geoCoder.getFromLocationName(addressStr, 
       1); 

     if (addresses.size() != 0) { 
      return addresses.get(0); 
     } 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

    return null; 
} 
+0

你有什麼日誌... –

回答

1

這是因爲當你沒有找到地址解析器的地址(即,如果addresses.size() == 0)你將返回null

然後,無論如何,您取消引用值,這是什麼崩潰您的應用程序。

Address targetAddress = getAddress(_ctx, strAddress); 
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
: 
if (targetLocation != null) { 
    targetLocation.setLatitude(targetAddress.getLatitude()); 
           ^^^^^^^^^^^^^ 

你或許應該還可以檢查targetAddressnull避免這種情況(無論是在除(可能)或代替(不太可能)的targetLocation,支票)。

所以我會看變化:

if (targetLocation != null) { 

到:

if ((targetLocation != null) && (targetAddress != null)) { 

這樣一來,一個無效的地址自動成爲有未位置。

+0

謝謝,它工作.......... – Nitish