在位置管理器中获取错误

时间:2014-05-28 18:07:06

标签: java android locationmanager

我试图找出当前的android设备的纬度和经度,但我得到了java.lang.nullpointerexception,app正在强制关闭。虽然我从这里获得了参考并使用了答案的代码被接受为正确: How to get Android GPS location 我的代码是:

try{
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
             Criteria criteria = new Criteria();
             String bestProvider = locationManager.getBestProvider(criteria, false);
             Location location = locationManager.getLastKnownLocation(bestProvider);


        double latit=location.getLatitude();
        double longit=location.getLongitude();
        Toast.makeText(getApplicationContext(),"Your Location is:\nLatitude:\t"+latit+"\nLongitude:\t"+longit,Toast.LENGTH_LONG).show();
            }catch(Exception ex){
                Toast.makeText(getApplicationContext(), "Error:"+ex,Toast.LENGTH_LONG).show();
            }

2 个答案:

答案 0 :(得分:0)

我敢打赌,您的location变量为空,这就是您获取NullPointerException的原因。当你调用LocationManager.getLastKnownLocation()时,如果没有最后的已知位置,它可以返回null。您最好的选择是使用LocationManager.requestLocationUpdates()方法之一请求位置更新并传入LocationListener

答案 1 :(得分:0)

您可以使用gps跟踪器类获取当前位置

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 = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = (1000 * 60 * 1)/6; // 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;
            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() {

    final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(true)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()

            {
            public void onClick(final DialogInterface dialog,
                        final int id) {
            Intent intent = new Intent(                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);

                }
            });

    final AlertDialog alert = builder.create();

    alert.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;
}

}

现在在您的活动中:

制作gps跟踪器类的对象

 GPSTracker gps = new GPSTracker(youractivity.this);
 double _mylats = gps.getLatitude();
 double _mylongs = gps.getLongitude();