2

I'm trying to get the location with the google-location services for android.

I've tried to fiddle with some methods from the google api from the tasks package, but all seem to fail. More exactly, my application starts to hang.

public class LocationTask extends AsyncTask<FusedLocationProviderClient, Void, JSONObject> {

    @SuppressLint("MissingPermission")
    @Override
    protected JSONObject doInBackground(FusedLocationProviderClient... locationProviderClients) {
        WeatherApiCall weatherApiCall = new WeatherApiCall();
        Task<Location> locationTask = locationProviderClients[0].getLastLocation();
        Location location = null ;
        try {
            location = Tasks.await(locationTask);
            weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
                    String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
            return new JSONObject(weatherApiCall.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

I've also tried to use the addOnSuccessListener, but to no avail.

try {
      locationProviderClients[0].getLastLocation()
         .addOnSuccessListener(location -> {
             if (location != null) {
                Log.d("LOCATION", location.toString());
                weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
                                    String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
                        }
                    });
            return new JSONObject(weatherApiCall.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

I know that the success listener does the action after the task locationProviderClients[0].getLastLocation() is successfully completed, but I fail to get the result from the task.

2eety
  • 89
  • 1
  • 13

0 Answers0