0

Hello I know this question is already existed but not getting my solution till now . I have tried many methods to get current location in android studio using java but all are showing the same message location is null and latitude longitude are showing 0.0/0.0

Kindly if any body knows the perfect solution to fix this problem ?

Phantômaxx
  • 37,352
  • 21
  • 80
  • 110

1 Answers1

5

You can use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        Toast.makeText(this, "longitude " + longitude + "latitude " + latitude, Toast.LENGTH_SHORT).show();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener); You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

You can add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

Saugat Jonchhen
  • 362
  • 5
  • 16