安卓谷歌地图V2当前位置纬度经度NullPointerException

3

有很多类似的问题,但我没有找到解决我的问题的方法。setUpMap方法如下:

private void setUpMap() {
    BitmapDescriptor iconm = BitmapDescriptorFactory.fromResource(R.drawable.m);
    BitmapDescriptor iconc = BitmapDescriptorFactory.fromResource(R.drawable.c);
    // Enable MyLocation Layer of Google Map
    mMap.setMyLocationEnabled(true);
    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();
    // Get the name of the best provider
    String provider;
    provider = locationManager.getBestProvider(criteria,true);
    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);
    // getting GPS status
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    // getting network status
    boolean isNWEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isNWEnabled)
    {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(getString(R.string.askposition) );
        dialog.setPositiveButton(getString(R.string.settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);
            }
        });
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
            }
        });
        dialog.show();
        // no network provider is enabled
        Log.e("Current Location", "Current Lat Lng is Null");
    }
    else
    {
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled){
            if (myLocation == null) {
                if (locationManager != null) {
                    myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    double latitude = myLocation.getLatitude();
                    double longitude = myLocation.getLongitude();
                    LatLng latlng = new LatLng(latitude, longitude);
                    //myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    //double latitude = myLocation.getLatitude();
                    //double longitude = myLocation.getLongitude();
                    //String lati = String.valueOf(latitude);
                    //String longi = String.valueOf(longitude);
                    // Create a LatLng object for the current location
                    //LatLng latlng = new LatLng(latitude, longitude);
                    // set map type
                    //mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    //CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(12).build();

                    //mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                    // Show the current location in Google Map
                   // mMap.moveCamera(newLatLng(latlng));
                    // Zoom in the Google Map
                    //mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                }
            }
        }
        else {
            // First get location from Network Provider
            if (isNWEnabled) {
                if (myLocation == null) {
                    if (locationManager != null) {
                        myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        double latitude = myLocation.getLatitude();
                        double longitude = myLocation.getLongitude();
                        LatLng latlng = new LatLng(latitude, longitude);
                        //double latitude = myLocation.getLatitude();
                        //double longitude = myLocation.getLongitude();

                        // Create a LatLng object for the current location
                        //LatLng latlng = new LatLng(latitude, longitude);
                        // set map type
                        //mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                        // Zoom in the Google Map
                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(12).build();

                        //mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        //mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                        // Show the current location in Google Map
                        //mMap.moveCamera(newLatLng(latlng));
                    }
                }
            }}
        }

    double latitude = myLocation.getLatitude();
    double longitude = myLocation.getLongitude();
    LatLng latlng = new LatLng(latitude, longitude);

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(11).build();
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

当我第一次从Android Studio运行应用程序到我的设备时,它能够正常工作,如果我关闭并重新启动应用程序也没有问题。 但是当我重新启动手机时,它会在double latitude = myLocation.getLatitude();处给出NullPointerException,并从那时起始终崩溃。 我该如何解决这个问题? 注释掉的代码行是几次尝试。但是问题仍然存在。 非常感谢您的任何帮助。


1
http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation%28java.lang.String%29。引用文档,如果提供者当前被禁用,则返回null。还请查看此链接http://gabesechansoftware.com/location-tracking/#comments。更新:http://developer.android.com/training/location/retrieve-current.html#GetLocation。 - Raghunandan
你可以通过使用try catch避免崩溃..将你的代码放在try catch中。 - Santosh Kathait
只是一个建议。如果你在使用Android Studio开发,你可以使用:https://github.com/mcharmas/Android-ReactiveLocation 来获取最新的融合位置。 - cYrixmorten
当您重新启动手机时,GPS 是否已启用? - Manny265
@Raghunandan 我正在查找,谢谢。Kat-hat 我会尝试,但我想知道为什么。cYrixmorten 谢谢您的建议,我稍后会尝试,希望能用现有的代码解决问题。Manny264 是的,它是网络和GPS两者都。 - Nonjoe
如果您在重新启动手机后尝试从getLastKnownLocation()获取位置,则值可能为null,您可能希望在设备重新启动后在onLocationChanged()方法中检索数据。 - ztan
2个回答

5
我认为解决您的问题的方法是使用 PASSIVE_PROVIDER

示例代码:

    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
    myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    double longitude = myLocation.getLongitude();
    double latitude = myLocation.getLatitude();

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        }
    }

似乎只使用网络关闭 GPS 提供程序就可以工作。 但是您的建议真的很有帮助!谢谢。 - Nonjoe

0

完整的解决方案,包括Marshmallow及以上版本的权限检查

//get location manger instance
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);


   //check if we have permission to access device location
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    //add location change listener with update duration 2000 millicseconds or 10 meters
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new LocationListener() {
        public void onLocationChanged(Location location) {
            currentLongitude = location.getLongitude();
            currentLatitude = location.getLatitude();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }

    });


    //get last known location to start with  
    Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);    
    currentLatitude = myLocation.getLatitude();
    currentLongitude = myLocation.getLongitude();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接