2014-04-28 3 views
-1

GPSTracker 클래스를 사용하여 현재 위치를 얻고 내 활동 클래스를 사용하여 현재 위치를 다른 4 시장 위치와 비교합니다. 그러면 가장 가까운 시장을 반환해야합니다. 다른 활동에서이 활동을 열려고 할 때, 나는 unfotunately 중지 된 오류가 발생했습니다 ..android 현재 위치 다른 위치를 비교하고 가장 가까운 위치를 반환합니다.

여기 내 코드; GPSTracker 클래스 :

여기
public class GPSTracker extends Service implements LocationListener { 

private final Context mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS(){ 
    if(locationManager != null){ 
     locationManager.removeUpdates(GPSTracker.this); 
    }  
} 

/** 
* Function to get latitude 
* */ 
public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* On pressing Settings button will lauch Settings Options 
* */ 
public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog Message 
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

    // On pressing Settings button 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog,int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    // on pressing cancel button 
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
     dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 

} 

내 활동 클래스 : 여기

public class ShoppingEnd extends Activity { 

    double [] distances; 
    double distanceToLemar, distanceToGulen, distanceToKas, distanceToSerin; 


    GPSTracker gps; 
    TextView cheapText, nearText; 

     Location currentLoc; 
     Location LemarLoc, GulenLoc , KasLoc , SerinLoc; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.shop_end); 

     cheapText =(TextView) findViewById(R.id.cheapest); 
     nearText =(TextView) findViewById(R.id.nearest); 


     nearText.setText(recommendByDistance()); 

    } 

    private String recommendByDistance() 
    { 
     getCurrentLocation(); 
     getMarketLocations(); 
     calculateDistances(); 

     Log.d("nearestt", getNearestMarket()); 
     return getNearestMarket(); 
    } 

    private void getCurrentLocation() 
    { 
     gps = new GPSTracker(ShoppingEnd.this); 
     if (gps.canGetLocation()) 
     { 
      double lat = gps.getLatitude(); 
      double lng = gps.getLongitude(); 

      currentLoc.setLatitude(lat); 
      currentLoc.setLongitude(lng); 

     } 
     else 
     { 
      gps.showSettingsAlert();   
     } 
    } 

    private void getMarketLocations() 
    { 
     double lemar_lat = 35.2478209 , lemar_lng = 33.0236201; 
     LemarLoc.setLatitude(lemar_lat); 
      LemarLoc.setLongitude(lemar_lng); 

      double gulen_lat = 35.2456597 , gulen_lng = 33.0352375; 
      GulenLoc.setLatitude(gulen_lat); 
      GulenLoc.setLongitude(gulen_lng); 

      double kas_lat = 35.2454282 , kas_lng = 33.0360717; 
      KasLoc.setLatitude(kas_lat); 
      KasLoc.setLongitude(kas_lng); 

      double serin_lat = 35.2456885 , serin_lng = 33.0360405; 
      SerinLoc.setLatitude(serin_lat); 
      SerinLoc.setLongitude(serin_lng); 
    } 

    private void calculateDistances() 
    { 
     distanceToLemar = currentLoc.distanceTo(LemarLoc); 
     distances[0] = distanceToLemar; 

      distanceToGulen = currentLoc.distanceTo(GulenLoc); 
     distances[1] = distanceToGulen; 

      distanceToKas = currentLoc.distanceTo(KasLoc); 
     distances[2] = distanceToKas; 

      distanceToSerin = currentLoc.distanceTo(SerinLoc); 
      distances[3] = distanceToSerin; 
    } 

    private String getNearestMarket() 
    { 

     Arrays.sort(distances); 
     if(distances[0]==distanceToLemar) 
      return "Lemar"; 
     else if(distances[0]==distanceToGulen) 
      return "Gulen"; 
     else if(distances[0]==distanceToKas) 
      return "Kas"; 
     else 
      return "Serin"; 
    } 

} 

로그 캣 :

04-28 18:47:35.274: E/AndroidRuntime(6771): FATAL EXCEPTION: main 
04-28 18:47:35.274: E/AndroidRuntime(6771): Process: com.ssa, PID: 6771 
04-28 18:47:35.274: E/AndroidRuntime(6771): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ssa/com.ssa.ShoppingEnd}: java.lang.NullPointerException 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread.access$800(ActivityThread.java:145) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.os.Handler.dispatchMessage(Handler.java:102) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.os.Looper.loop(Looper.java:136) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread.main(ActivityThread.java:5081) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at java.lang.reflect.Method.invokeNative(Native Method) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at java.lang.reflect.Method.invoke(Method.java:515) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at dalvik.system.NativeStart.main(Native Method) 
04-28 18:47:35.274: E/AndroidRuntime(6771): Caused by: java.lang.NullPointerException 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at com.ssa.ShoppingEnd.getMarketLocations(ShoppingEnd.java:69) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at com.ssa.ShoppingEnd.recommendByDistance(ShoppingEnd.java:41) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at com.ssa.ShoppingEnd.onCreate(ShoppingEnd.java:32) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.Activity.performCreate(Activity.java:5231) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169) 
04-28 18:47:35.274: E/AndroidRuntime(6771):  ... 11 more 
+0

액세스하는 위치는 초기화하지 않습니다. 당신의 충돌을 야기하고있는 것들에 접근하려 할 때 null이 될 것입니다. – dymmeh

답변

2

처음에 setLatitude를 호출 할 때 당신은 당신의 위치 변수를 초기화하지, 그래서 그들은 널 (null)입니다 하나. 따라서 NullPointerException.

대문자로만 클래스 이름을 시작하는 것도 규칙입니다. 변수는 소문자로 시작하는 낙타의 경우 여야합니다.

Location lemarLoc = new Location(""); 
+0

currentLoc = new Location (currentLoc); , lemarLoc = 새 위치 (lemarLoc); 등등. 그러나 충돌 여전히 동일하게 유지됩니다 : ( – cmnl

+0

그냥 생성자에 전달하는 인수에서 위치를 복사합니다, 그래서 당신이 무언가에서 복사하여 초기화하려고합니다. 빈 문자열 인수로 그들을 초기화하십시오. – Hober

+0

당신의 대답 주셔서 감사합니다. 그러나 주된 문제의 두 번째 이유는 배열입니다. 나는 배열을 삭제하고 if/elses와 거리 비교를 수행 한 다음 올바르게 실행됩니다. 왜 배열이 널 포인터를 가져 오는지 알지 못합니다. 배열 및 다른 사람의 초기화 직원) 어쨌든, 다시 한번 감사드립니다 .. – cmnl

관련 문제