0

Someone please suggest a code to get gps location(latitude and longitude) of a android device in android. I tried so many examples but in

Location location = locationManager.getLastKnownLocation(bestProvider);

getting location=null.
I am posting my code below.

public class MainActivity extends AppCompatActivity {


Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat,lng;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    bestProvider = lm.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = lm.getLastKnownLocation(bestProvider);

    if (location == null)
    {
        Toast.makeText(this,"Location Not found",Toast.LENGTH_LONG).show();
    }
    else{
        geocoder = new Geocoder(this);
        try
        {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            lat=(double)user.get(0).getLatitude();
            lng=(double)user.get(0).getLongitude();
            System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}


}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
stan wyck
  • 9
  • 6
  • to get GPS location you need to ennable gps.Do you do it in your app? – Kevin Kurien Feb 01 '19 at 08:53
  • 1
    `location=null` means you are calling that code too early, and it still did not determine the location. Use location listener\ – Vladyslav Matviienko Feb 01 '19 at 08:54
  • 1
    Possible duplicate of [How to get Latitude and Longitude of the mobile device in android?](https://stackoverflow.com/questions/2227292/how-to-get-latitude-and-longitude-of-the-mobile-device-in-android) – Madhur Feb 01 '19 at 09:04
  • GPS is enabled and location is called inside main activity.still location=null. – stan wyck Feb 01 '19 at 09:15

0 Answers0