Reputation: 1
I am having trouble figuring out why my app force closes when GPS is not enabled. When enabled before running, all is well. Everything worked fine until I added the LocationListener to update current location. I'm sure it is something ridiculously simple.
public class GlenrochieMain extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//GPS Functionality
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
//Criteria for GPS
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
//updates location every 5second+5meters
locationManager.requestLocationUpdates(provider, 5000, 5,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Location is:\n" +
latLongString);
}
}
Upvotes: 0
Views: 1109
Reputation: 18068
String provider = locationManager.getBestProvider(criteria, true);
When no suitable provider is found, getBestProvider will return null. You have not handled that case.
Upvotes: 0
Reputation: 359776
You need to make sure that the GPS is actually enabled. This answer is for Android 1.6, see How can I check the current status of the GPS receiver? for later versions.
Upvotes: 1