2012-09-11 3 views
0

내 앱에서 특정 위치가 지정된 지역에 있는지 여부를 알아야합니다. 나는 Connaught Place, New Delhi를 중심점으로 삼고 있습니다. 중심점에서 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을 반환합니다.

그런 다음에 관계없이 값을 역 참조하면 앱이 충돌합니다. 당신은 아마이 (중 targetLocation의 체크 (가능성), 또는 대신 (덜)에 추가로)을 방지하기 위해 null에 대한 targetAddress을 확인해야

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

.

그래서 변화에서 찾고있을 것 :

if (targetLocation != null) { 

로 :

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

그 방법을, 잘못된 주소가 자동으로 unserviced 위치가된다.

+0

감사합니다. 작동했습니다 .......... – Nitish

관련 문제