Wait for multiple asynchronous calls to Places API functions (Google API) – Android-ThrowExceptions

Exception or error:

I’m using the Places API in Android Studio (Java). I want to compute the distance between a Place “place1” and several other Places place2, of which I have their ID.

public void computeDistances(){

    for(int i = 0; i < addresses.size() ; ++i){

        String id = addresses.get(i).getplaceID(); // get id of place2

        // Construct a request object, passing the place ID and fields array.
        List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
        FetchPlaceRequest request = FetchPlaceRequest.newInstance(id, placeFields);

        // get place
        PlacesClient placesClient = Places.createClient(getContext());
        placesClient.fetchPlace(request).addOnSuccessListener((response) -> {

            Place place2 = response.getPlace();

            LatLng LatLng1 = new LatLng(place1.getLatLng().latitude, place1.getLatLng().longitude);
            LatLng LatLng2 = new LatLng(place2.getLatLng().latitude, place2.getLatLng().longitude);

            double distance = SphericalUtil.computeDistanceBetween(LatLng1, LatLng2);
            Log.e(TAG, "Distance  = " + distance);

        }).addOnFailureListener((exception) -> {
            if (exception instanceof ApiException) {
                ApiException apiException = (ApiException) exception;
                int statusCode = apiException.getStatusCode();
                Log.e(TAG, "Place not found: " + exception.getMessage());
            }
        });

    }


}

Problem:
I want to compute all these distances, store them in an array, and finally using them to make some other computations. I know these calls are asynchronous, but I’m not able to find a way to store all the distances in an array, and then, when all the calls are completed, continue running my code.

Thanks in advance.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *