0

I am implementing a simple app that uses locationmanager to get current latitude and longitude of device. I am using below code:

  LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

            if (location != null){
                latti = location.getLatitude();
                longi = location.getLongitude();
                Toast.makeText(this,"Lat: "+latti+"Lng"+longi,Toast.LENGTH_LONG).show();

            } else {

                Toast.makeText(this,"null",Toast.LENGTH_LONG).show();

            }

The problem is that this code always gives null even though I have turned GPS and have internet connection. However if I first open the google maps application and search for my current location then open my app only then above code shows correct latitude and longitude.

I have used plenty of codes from stackoverflow and other websites but all have same issue. Can anybody help please?

U.Ahsan
  • 55
  • 1
  • 10
  • It is null because there is no location cached and opening Google Maps caches a new location. – David Medenjak Sep 14 '17 at 18:16
  • Last known location returns null when there is no last known location. There is a good tutorial on Android hive website to fetch location from GPS . You should see that – Vivek Mishra Sep 14 '17 at 18:19

0 Answers0