Tran Hoai Nam Tran Hoai Nam - 3 months ago 34
Android Question

Get GPS location in AsyncTask

I have an

AsyncTask
class that needs to get user's location when this
AsyncTask
is called.

The idea is to check if location service is enabled or not, if not, the location service toggle will popup for user to turn it on, then it will go back to the task to continue getting the location and finish the job.

However, the code below show
NullPointerException
on the line
lat = location.getLatitude();
near the end of
onPreExecute()
. They said because
getLastKnownLocation
gets nothing as it's just been turned on a moment ago, then how can I get the location right after the location service has been turned on?

LocationManager locationManager;
LocationListener locationListener;
double lat;
double longi;

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}

@Override
protected void onPreExecute() {
super.onPreExecute();
location = new Location(LocationManager.NETWORK_PROVIDER);
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}

//I copy the part below from the internet but seems like "onProviderDisabled" and "onLocationChanged" were never be called
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",location.getLatitude()+"_"+location.getLongitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};


locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0, locationListener);
lat = location.getLatitude();
longi= location.getLongitude();
Log.v("GPS Cord CHECK",lat+"_"+longi);

}

@Override
protected String doInBackground(final Checkout_Package... params) {
//Doing the job that needs lat and longi value!
}


Thank you for your time!

Answer

You cannot create and put a location listener in onPreExecute() because the onChanged handlers will only be invoked much later when onPostExecute or even your AsyncTask has finished.

What you should do instead is start an AsyncTask in that location changed handler.

So in onLocationChanged().

Comments