1

I am trying to use FusedLocationProviderClient to get the Latitude and Longitude of the current location. My code so far is as follows:

Manifest

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

Layout: have a button

build.gradle

implementation 'com.google.android.gms:play-services-location:16.0.0'

Java

ArrayList<String> Coord_Array;

Inside OnCreate method

private FusedLocationProviderClient client;
client = LocationServices.getFusedLocationProviderClient( ShowOutletParams.this );
Coord_Array = new ArrayList<String>();

Outside OnCreate method - I am using getLocation() inside the button onclicklistener

private String getLocation() {
        if (ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        client.getLastLocation().addOnSuccessListener( ShowOutletParams.this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    String locat = location.toString();
                    String lat = locat.substring(15,24);
                    String longi = locat.substring(25,34);
                    Coord_Array.add(lat);
                    Coord_Array.add(longi);
                    //return Coord_Array;
                }
            }
        } );

    }

When I add Log.i to log the lat and long values, I could see them in the log, however I want them to be saved as strings, which I want to use later.
I understand void does not return anything....however the Coord_Array too doesn't return or print the lat and long.

Apricot
  • 2,925
  • 5
  • 42
  • 88

3 Answers3

1

You should try :

client.getLastLocation().addOnSuccessListener( ShowOutletParams.this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
                    if (location != null) {
                        double mLatitude = location.getLatitude();
                        double mLongitude = location.getLongitude();                           
                    }
                });
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }}

if still facing issue check for the tutorial

Arjun Vyas
  • 409
  • 5
  • 14
1

The main problem is your method private String getLocation() returns before any Location is actually available (and I'm pretty sure it won't compile by looking at it).

When you're here:

if (ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
   return;
}

you're still in the standard flow of your method. But once you get passed here:

client.getLastLocation().addOnSuccessListener(

all of the code within your public void onSuccess(Location location) is now running AFTER your call to getLocation() has already returned!

A simple solution is to pass in callbacks into your getLocation() method, so that they can be triggered after the method has already returned to its caller, e.g.

public interface LocationAvailableListener {
    public void onLocationAvailable(Location location)
}

public void getLocation(LocationAvailableListener locationAvaialbleCallback, Runnable locationNotAvailableCallback) {
...

Then when checking permissions, you can now trigger your failure callback:

if (ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( ShowOutletParams.this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
   locationNotAvailableCallback.run();

   return;
}

and then in your onSuccess

if (location != null) {
   locationAvaialbleCallback.onLocationAvailable(location);
}
else {
   locationNotAvailableCallback.run();
}

And then to use:

getLocation(
   location -> {
      String latitude = String.valueOf(location.getLatitude());
      String longitude = String.valueOf(location.getLongitude());

      // Add to your ArrayList here
      // Save to your database or wherever for later
   },
   { Log.i(TAG, "Failed to get Location"); })

And since you asked about persisting the Location data once you have it, this reference should point you in the right direction with some simple JSON serialization.

Cruceo
  • 6,763
  • 2
  • 31
  • 52
0

You have to get Longitude and Latitude directly from the location object and cast it to string as you want.

in Kotlin :

lat = location.latitude.toString()

and in Java :

lat = location.getLatitude() + "";

Shynline
  • 1,497
  • 1
  • 13
  • 18