0

I am using the code below to get the current location of an individual both the longitude and latitude values

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    assert locationManager != null;
    Location location1 = locationManager.getLastKnownLocation(Objects.requireNonNull(locationManager.getBestProvider(criteria, true)));
    Geocoder geocoder=new Geocoder(getBaseContext(), Locale.getDefault());
    List<Address> addresses;

    try {
        addresses=geocoder.getFromLocation(Objects.requireNonNull(location1).getLatitude(),Objects.requireNonNull(location1).getLongitude(),1);
        if(addresses.size()>0){
            location.setText(addresses.get(0).getLocality());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

when i run the app , it crashes and when i check the debugger it shows

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference

This error is at a line after the try method opening bracket and i have tried to avoid getting null values using the refractors available but my app still crashes. some assistance would be nice on how to overcome this problem. Thank you

Gustavo
  • 5,586
  • 5
  • 38
  • 68
jaiveon38
  • 15
  • 5

0 Answers0