How can I cat latitude and longitude of Android device?

1.1k Views Asked by At

So I'm making this app which finds restaurants near you, fetching information from a food-delivery app, using JSoup library. The only problem with it is that sometimes the latitude and the longitude are getting null value. Situations in which my application is working: -turning on GPS and the waiting at least 1-2 minutes; -opening google maps, closing it, and then returning to the application;

So the main problem: I can't fetch the location right after I enable it and hit the 'Find restaurants' button, I need to wait 1-2 minutes after enabling location, then it's working.

    private TextView result;
    private FusedLocationProviderClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestPermission();
        client = LocationServices.getFusedLocationProviderClient(this);

       getBtn = findViewById(R.id.getRestaurants);
       result = findViewById(R.id.restaurantsList);

       getBtn.setOnClickListener(this);
    }



    private void requestPermission(){
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1 );
    }


public void onClick(View v) {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                return;
        }

        client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                result.setText("Getting location...");
                if(location != null){
                double latitude = getLat(location);
                double longitude = getLng(location);

                    result.setText("Finding restaurants near you...");
                getWebsite(latitude, longitude);
                }else{
                    result.setText("Couldn't fetch location!");
                }

            }
            });
2

There are 2 best solutions below

1
On

you must use requestLocationUpdates() you are using getLastLocation() and when the GPS is off and turned on after the last known location becomes null so you must call requestLocationUpdates() you can find more information in the below link

https://developer.android.com/training/location/receive-location-updates

0
On

Here is a good way to implement the FusedLocationProvider in Kotlin (you might adapt to Java or use Java and Kotlin side by side) :

private fun startLoc() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        try {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    //showDialog(this@MapsActivity, TAG, "last know loc = ${location?.latitude} + ${location?.longitude}")
                    if (location != null){
                        lastKnowLoc = LatLng(location.latitude, location.longitude)
                        addMarkerToLocation(lastKnowLoc)
                    }
                }
            val locationRequest = LocationRequest()
            locationRequest.interval = 10000
            locationRequest.fastestInterval = 10000
            locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

            locationCallback = object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult?) {
                    locationResult ?: return
                    for (location in locationResult.locations){
                        //showDialog(this@MapsActivity, "locationResult", "location=${location.latitude};${location.longitude}")
                        addMarkerToLocation(LatLng(location.latitude, location.longitude))
                        val speed = location.speed
                        updateCamera(location.bearing)
                    }
                }
            }

            fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)

            btnStartLoc.isEnabled = false
            btnStopLoc.isEnabled = true
        }catch (e:SecurityException){}

    }