3

Есть много подобных вопросов, но я не нашел решения для своей проблемы. Метод setUpMap является:Android Google Maps V2 текущая позиция широта долгота NullPointerException

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 на устройство, а также отлично работает, если я закрыть и перезапустить приложение. Но когда я перезагружаю свой смартфон, он дает мне NullPointerException @double latitude = myLocation.getLatitude(); , и с этого момента он всегда сбой. Как я могу это исправить? Прокомментированные строки кода - это несколько попыток. Такая же проблема. Любая помощь будет высоко оценена. Спасибо заранее.

+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

+0

вы можете избежать сбоя, используя try catch..put ваш код внутри try catch –

+0

Просто предложение. Если вы работаете в Android Studio, вы можете использовать: https://github.com/mcharmas/Android-ReactiveLocation, чтобы получить последнее заблокированное местоположение – cYrixmorten

ответ

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

Кажется, это работает, отключив GPS-провайдер, используя только сеть. Но ваше предложение действительно полезно! Спасибо – Nonjoe

+0

хороший фрагмент кода, работающий без головной боли :) –

0

Комплексное решение, включая проверку разрешений на Зефир и выше

//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(); 
Смежные вопросы