I have looked everywhere I possibly can and found nada. It's been a few hours that I am trying to solve this thing out yet no luck. I have a function that is meant to acquire my location once through requestLocationUpdates and then getLastKnownLocation. Now here is the thing. If the Location Services on the phone are disabled it pops up an alertDialog asking if the user would like to activate it and if he does it takes him to the settings window. In case where the services are off and the user goes to the settings window, activates them and then retries to use the function something weird happens. I later use the location I am desperately trying to get here in the following activity but it's a reference to null so it crashes. If I run the app normally it would crash with the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'float android.location.Location.distanceTo(android.location.Location)' on a null object reference
If I debug the app, it works just fine. And if I start a 3000 millis sleep timer between the requestLocationUpdates and getLastKnownLocation it sometimes works and sometimes it does not. I would LOVE some help, because I am just clueless.
I am using the AsyncTask because I thought it is happenning because the device does not manage to finish requestLocationUpdates() before it reaches getLastKnownLocation() so I used AsyncTask and .get() it so it waits till it finishes.
Below are the codes.
Location receiver
ArrayList<ArrayList<String>> teachers = Client.getTeachers();
Location loc;
loc = gpsOps.getLocation();
Intent i = new Intent(getApplicationContext(), teachersScreen.class);
i.putExtra("teachers", teachers);
i.putExtra("location", loc);
startActivity(i);
gpsOps.getLocation
public static Location getLocation()
{
try {
new AsyncGetLocation().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = providers.size() - 1; i >= 0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
return l;
}
requestLocationUpdates
public class AsyncGetLocation extends AsyncTask<Void,Void,Void> {
private ProgressBar dialog = null;
private Location loc = null;
@Override
protected void onPreExecute()
{
}
@SuppressLint("MissingPermission")
@Override
protected Void doInBackground(Void... Void)
{
Log.e("doInBackground", "Entered getLocation");
gpsOps.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0.0f, gpsOps.ls, Looper.getMainLooper());
return null;
}
@Override
protected void onPostExecute(Void aVoid)
{
}
Faulty command sequence
tempLoc = locs.get(teachers.get(x).get(3));
if(loc.distanceTo(tempLoc) <= 30*1000)
rangeFlag = true;
else
rangeFlag = false;