Adaephon Ben
Adaephon Ben

Reputation: 27

Why is this code (which uses FusedLocationProviderClient to get the User's location) not working?

I want to find the current Latitude and Longitude of the user, as accurately as possible and display this data on a TextView in my MainActivity. However, the App always returns 0.0, 0.0 as the latitude and longitude.

I've tried fixing my AndroidManifest as well as giving appropriate Location permissions to the app manually.

public class MainActivity extends AppCompatActivity {
TextView mTextViewLocation ;
boolean permission ;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
private double Latitude ;
private double Longitude ;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupGPS();
    mTextViewLocation = (TextView)findViewById(R.id.textViewLocation);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(60000);
    mLocationRequest.setFastestInterval(20000);
    mLocationRequest.setMaxWaitTime(60000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null){
                Log.d("Location: GPS","off");
                return;
            }
            for (Location location : locationResult.getLocations()) {
                Log.d("locations : " ,location.getLatitude()+"");
                Latitude = location.getLatitude();
                Longitude = location.getLongitude();
            }
        }
    };
    String s = Latitude + " " + Longitude ;
    mTextViewLocation.setText(s);
}
public void setupGPS() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            if(PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
                permission=true;
                mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                        mLocationCallback,null);
            }
            else {
               permission=false;
                AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
                alert.setTitle("Permission Denied");
                alert.setMessage("You need to enable location permissions for this app.");
                alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        permission = true ;
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                608);
                    }
                });
                alert.setNegativeButton("Later", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        permission=false;
                    }
                });
                alert.create().show();
            }
        }
    });
    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            607);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}

}

I want this to display my Accurate location, in terms of latitude and longitude, but it just displays "0.0 0.0" now.

These are the permissions I've given the app in AndroidManifest:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" /> 

I've also included this in my app's Build.gradle :

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

Upvotes: 1

Views: 1317

Answers (1)

Vivek
Vivek

Reputation: 106

String s = Latitude + " " + Longitude; mTextViewLocation.setText(s);

is outside of onLocationResult() methode call back. Since mTextViewLocation.setText(s); is called before onLocationResult() method, you are getting wrong valuew in the text view.

Here are the steps to get the location of the device:

  1. Add dependency in your app level gradle file: implementation com.google.android.gms:play-services-location:16.0.0

  2. Be sure to add permission in the Menifest file:

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

  3. Then you can get the location using the below code:


 LocationRequest request = new LocationRequest();
            request.setInterval(10000);
            request.setFastestInterval(5000);
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            FusedLocationProviderClient client = 
         LocationServices.getFusedLocationProviderClient(this);
            int permission = ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION);   
            if (permission == PackageManager.PERMISSION_GRANTED) {   
                    // Request location updates and when an update is 
                    // received, update text view    
                    client.requestLocationUpdates(request, new LocationCallback() {         
                            @Override  
                        public void onLocationResult(LocationResult locationResult) {                           
                            Location location = locationResult.getLastLocation();  
                            if (location != null) {   
                                    // Use the location object to get Latitute and Longitude and then update your text view.  
                            }  
                        }  
                    }, null);  
                }

Upvotes: 1

Related Questions