I have an application in which I need to get the device location , in my code after getting the device's location i store them in shared preferences and then after clicking on a button I retrieve the latitude and longitude and use them in other method calls , but sometimes after activating the GPS and calling the "getCurrentLocation" method (Listed below) , I got error saying that the latitude and longitude values stored in shared prefs are null even if I made a loading screen that lasts 8 seconds after calling the getCurrentLocation method in order to wait for to return value , how to make my app wait for the getCurrent Location methid untill it returnsa value ??
Lets say that I am calling it on the OnCreate lifecycle method or onButton click , how to wait for it to return a value ??
public void getCurrentLocation(Activity currentActivity) {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setFastestInterval(5000);
request.setPriority(request.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client =
LocationServices.getFusedLocationProviderClient(currentActivity);
int permission = ContextCompat.checkSelfPermission(currentActivity,
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.
currentLocation = location;
sharedPreferences = getSharedPreferences(getPackageName() + ".prefs", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("lat", String.valueOf(location.getLatitude()));
editor.putString("lng", String.valueOf(location.getLongitude()));
editor.apply();
// Intent i = new Intent(currentActivity,Loading.class);
// startActivity(i);
}
}
}, null);
}
}
Location Data on Maps SDK for Android has the
ActivityCompat.OnRequestPermissionsResultCallback
callback function which you can utilize to check if you have accessed the device location or not.For example: