在我的應用程序中,我必須查找給定位置是否在指定區域下。我以新德里康樂廣場爲中心點。並且我得到了離中心點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;
}
你有什麼日誌... –