LocationManager выбрасывает NullPointerExpection - программирование

LocationManager выбрасывает NullPointerExpection

Пожалуйста, у меня есть этот код, который работал у меня все это время, и он внезапно не работает, он возвращает null pointer exception в

double lat = (double) (lastKnownLocation.getLatitude());.

Я установил все необходимые разрешения в файле манифеста, но, похоже, он не работает снова. Я думаю, что теперь проблема с использованием поставщика GPS.

    latituteField = (TextView) findViewById(R.id.TextViewLatitudeValue);
    longitudeField = (TextView) findViewById(R.id.TextViewLongitudeValue);
    SpeedField = (TextView) findViewById(R.id.textViewSpeedValue);
    AltitudeField = (TextView) findViewById(R.id.textViewAltitudeValue);        
    AddressLabel=(TextView)findViewById(R.id.textViewAddress);
    lbllatitude=(TextView)findViewById(R.id.lblLatDMS);
    lbllongitude=(TextView)findViewById(R.id.lblLongDMS);



    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // GPS_PROVIDER
    String locationProvider = LocationManager.GPS_PROVIDER;  
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

    // check if enabled and if not send user to the GSP settings
    // Better solution would be to display a dialog and suggesting to 
    // go to the settings
    if (!enabled) 
    {           
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      startActivity(intent);

    }
    else if (locationProvider!= null) 
    {
     Toast.makeText(this, locationProvider +" has been selected",Toast.LENGTH_SHORT).show();
      onLocationChanged(lastKnownLocation);
    } 
    else 
    {
      latituteField.setText("0.00");
      longitudeField.setText("0.00");
      AltitudeField.setText("0.00");
      SpeedField.setText("0.00");

    }

  }

  /* Request updates at startup */
  @Override
  protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
  }

  /* Remove the locationlistener updates when Activity is paused */
  @Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
  }

  @Override
  public void onLocationChanged(Location lastKnownLocation) {

    double lat = (double) (lastKnownLocation.getLatitude());
    double lng = (double) (lastKnownLocation.getLongitude());
    double Alt = (double) (lastKnownLocation.getAltitude());
    double Speed = (double) (lastKnownLocation.getSpeed());

    latituteField.setText(String.format("%.5f",lat));
    longitudeField.setText(String.format("%.5f",lng));
    AltitudeField.setText(String.format("%.5f",Alt));
    SpeedField.setText(String.format("%.5f",Speed));
4b9b3361

Ответ 1

LastKnownLocation вернет значение null, если либо его местоположение слишком устарело, либо если поставщик никогда не был включен. Вы должны принять это во внимание. Единственный способ убедиться в правильности местоположения - запросить обновления и получить его в onLocationChanged.

Кроме того, lastKnownLocation может вернуть значение, которое очень неправильно - возможно, с 10 или 15 минут назад. Вы можете использовать его, но не ожидайте точности.