I’m new to Java and Android development. The task is to get user’s location (which was reached), I got the result of 50.28.. in variable "lat"
BUT
as far as I am trying to print this variable outside the function OnSuccess I get the value null.
Due to the lack of knowlendge I can only assume the problem is in synchronization as OnSuccess needs more time to run and till the moment of printing the text it’s still not initialized. However I’m not sure if I understand the problem correctly and would like to ask for a short explanation on how it works.
How can I use the result of OnSuccess further on in my program?
FusedLocationProviderClient fusedLocationProviderClient;
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(mainActivity);
Double lat = null; // variable for storing latitude
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
/** If we have permission -> get location */
if(mainActivity.getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
// get the location
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null)
{
lat = location.getLatitude(); // = 50.28...
}
}
});
}
}
binding.lat.setText(String.valueOf(lat)); // = null
Source: Android Questions