requestLocationUpdates() needs to be in try/catch (Android Studio 3.0)

#1

For this chapter, I’m using my device and not an emulator, and I’m also using Android Studio 3.0 Canary 3. All the code works great except this part gives me error if I don’t put it in try/catch with SecurityException:

LocationServices.FusedLocationApi
.requestLocationUpdates(mClient, request, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, "Got a fix: " + location);
new SearchTask().execute(location);
}
});

Code now reads:

        if (hasLocationPermission()) {
        try {
            LocationServices.FusedLocationApi
                    .requestLocationUpdates(mClient, request, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            Log.i(TAG, "Got a fix: " + location);
                            //Now that you have a location fix, use it.
                            //  Asynctask find GalleryItem near your location
                            //  fix, download its associated image, and display it
                            new SearchTask().execute(location);
                        }
                    });
        } catch (SecurityException ex) {
            Log.e(TAG, "Error creating location service: " + ex.getMessage());
        }
    }
1 Like
Location permission dialog wont show
#2

Hm. Interesting. When I look at the docs: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi.html#requestLocationUpdates(com.google.android.gms.common.api.GoogleApiClient, com.google.android.gms.location.LocationRequest, com.google.android.gms.location.LocationListener)

The only place that I see where something throws a SecurityException is when dealing a mock location provider. I’ll have to do some more digging.

Also, when you log exceptions, consider using the 3 parameter version of the log methods so that you’ll get a full stacktrace (and the exception message):

Log.e(TAG, "Error creating location service", ex);