android当前位置比较其他位置并返回最近的位置

时间:2014-04-28 15:50:15

标签: java android nullpointerexception location

我使用GPSTracker类来获取当前位置和我的活动类别来比较当前位置与其他4个市场位置然后它应该返回最近的市场。当我想从另一个活动打开这个活动时,我得到了错误,不幸的是停止了..

这是我的代码; 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";
    }

}

这里是logcat:

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

1 个答案:

答案 0 :(得分:2)

您永远不会初始化您的位置变量,因此当您在第一个上调用setLatitude时它们为null。因此,NullPointerException。

通常只使用大写字母启动类名。变量应该是驼峰式的,从小写字母开始:

Location lemarLoc = new Location("");