简体   繁体   English

在位置管理器中出现错误

[英]Getting error in the location manager

I am trying to find out current latitude and longitude of android device but I am getting java.lang.nullpointerexception and app is force closing.even though i get refrence from here and used the code from the answer which was accepted as correct: How to get Android GPS location my code is: 我试图找出Android设备当前的经纬度但我正在逐渐显示java.lang.NullPointerException和应用程序是力closing.even虽然我从这里得到refrence并用从被接纳为正确答案代码: 如何获取Android GPS位置,我的代码是:

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();
            }

I would bet that your location variable is null and that's why you're getting the NullPointerException . 我敢打赌,您的location变量为null,这就是为什么要获取NullPointerException的原因。 When you call LocationManager.getLastKnownLocation() it can return null if there is no last known location. 当您调用LocationManager.getLastKnownLocation() ,如果没有最后一个已知位置,它可以返回null。 Your best bet is to request location updates using one of the LocationManager.requestLocationUpdates() methods and passing in a LocationListener . 最好的办法是要求使用的一个位置更新LocationManager.requestLocationUpdates()方法,并传递一个LocationListener

you can use the gps tracker class to get current location 您可以使用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;
}

}

now in your activity: 现在在您的活动中:

make a object of gps tracker class 使gps跟踪器类成为对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM