0

I am trying to find my device location but it always returning null. Below is my code.

    public Location getLocation() {

    if (ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(context, "Permission is not granted", Toast.LENGTH_LONG).show();
        return null;
    }
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    assert locationManager != null;
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (isGPSEnabled) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
        return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } else {
        Toast.makeText(context,"Please enable GPS",Toast.LENGTH_LONG).show();
    }
    return null;
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Shah Alam
  • 23
  • 8
  • The `requestLocationUpdates()` call is [asynchronous](https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean) and the results are not available immediately, so calling `getLastKnownLocation()` right after it is not the way to get the location in Android although some bad code examples suggest it. Wait for the `onLocationChanged()` callback. – Markus Kauppinen Jun 08 '18 at 14:33
  • Possible duplicate of [What is the simplest and most robust way to get the user's current location on Android?](https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-on-a) – Markus Kauppinen Jun 08 '18 at 14:35

0 Answers0