0

I'm trying to get the user location with location manager but the location always returns null. I also am asking to the user to turn on the gps.

This is my code:

   int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);

    if(permisioncheck == 0){

        lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);

        List<String> providers = lm.getProviders(true);

        Location bestLocation = null;

        for (String provider : providers) {
            Location location = lm.getLastKnownLocation(provider);
            if (location == null) {
                continue;
            }

            if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = location;
            }
        }

        if(bestLocation == null){
            System.out.println("is NULL!");
        }
    }else{

        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }

I hope that someone could help me to find the error, thanks.

1 Answers1

3

The "error" is that you are assuming that getLastKnownLocation() will return a Location. Frequently, it will return null. Use getLastKnownLocation() as a possible optimization, but otherwise you need to requestLocationUpdates(), then use the location in the onLocationChanged() method.

See this sample project and the documentation for more.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491