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