有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在位置管理器中获取错误

我试图找出安卓设备的当前纬度和经度,但我得到了java。lang.nullpointerexception和应用程序正在强制关闭。尽管我从这里得到了参考,并使用了答案中的代码,该答案被认为是正确的: 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) 个答案

  1. # 1 楼答案

    您可以使用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();
    
  2. # 2 楼答案

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