In my app I fetch GPS coordinates from the user. When the GPS was just activated my app continues even before the coordinates were fetched, so the location is null. I noticed that the onLocationChanged method does as it should and might somehow be a key to it, but how do I make sure that the code in the main class doesn’t fetch empty values and waits until the location is not null?
The main code:
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSFetch t = new GPSFetch(getActivity().getApplicationContext());
Location location = t.getLocation();
if (location == null) {
//Toast
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
The GPSFetch:
public Location getLocation(){
if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED)
{
return null;
}
try {
LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
}else{
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
public void onLocationChanged(Location location) {
Log.d("4", "changed");
}