0

So i want to display my latitude and longitude of the position, however it shows me only when i launch the app again. When i install the app, and launch it for the first time there is no position received. What is the simple way to get the current location for the first time? What i am doing wrong? I run this on emulator with API 24.

Here is my code:

private final static String LOG_TAG = MainActivity.class.getName();
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
private TextView locationLatitude;
private TextView locationLongitude;

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

    locationLatitude = (TextView) findViewById(R.id.latitude_text);
    locationLongitude = (TextView) findViewById(R.id.longitude_text);

    buildGoogleApiClient();
}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    googleApiClient.disconnect();
}

private void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.d(LOG_TAG, "onConnected");
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    if(Build.VERSION.SDK_INT < 21){
        lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    }
    else {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        else{
            lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        }
    }


    if(lastLocation != null){
        locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
        locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 1){
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            }
        }
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.d(LOG_TAG, "onConnectionSuspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(LOG_TAG, "onConnectionFailed");
}

@Override
public void onLocationChanged(Location location) {
    Log.d(LOG_TAG, "onLocationChanged");
    locationLatitude.setText(String.valueOf(location.getLatitude()));
    locationLongitude.setText(String.valueOf(location.getLongitude()));
}
K.Os
  • 5,123
  • 8
  • 40
  • 95
  • Sometimes the last location is not available and will be null. Consider saving the last location in a preference for this scenario or falling back to the process that is followed when the app is first downloaded. – danny117 Feb 20 '17 at 14:50

1 Answers1

0

You never request location updates.

Try this:

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.d(LOG_TAG, "onConnected");
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
            googleApiClient, locationRequest, this);


    if(Build.VERSION.SDK_INT < 21){
        lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    }
    else {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
        else{
            lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        }
    }


    if(lastLocation != null){
        locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
        locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
    }
}
Cedric Franck
  • 526
  • 4
  • 9
  • I've changed my onConnected method to yours, but now app crashs and this is the exception': java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.' However i have this permission in my manifest. – K.Os Feb 20 '17 at 15:20
  • Can you show the implementation of your permissions? – Cedric Franck Feb 20 '17 at 15:43
  • I've just put this `LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest, this);` in the same place where i request for getLastLocation. There is no exception now, but still I have the same issue as on the beggining. I only change my onConnected method, rest is like on the beginning of my question(I provided whole code) – K.Os Feb 20 '17 at 15:53
  • 1
    The `requestLocationUpdates()` method call is asynchronous and its results are not immediately available, so just calling `requestLocationUpdates()` and `getLastLocation()` right after it won't give you the location. Wait for the `onLocationChanged()` callback to be triggered instead. It may take tens of seconds (with GPS) or never happen if the device is indoors. – Markus Kauppinen Feb 20 '17 at 17:24