location manager android problem
I am trying to get a user's location when a button is clicked.
I have the following code in my button onclick listener:
locationManager = (LocationManager) getS开发者_Python百科ystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location currentLocation = locationManager.getLastKnownLocation(bestProvider);
Log.e(tag,"reached till here");
location = Double.toString(currentLocation.getLatitude()) + " " + Double.toString(currentLocation.getLongitude());
Toast.makeText(getApplicationContext(), location, Toast.LENGTH_LONG);
MyLocation.setText(location);
I am getting the the output reached till here
in logcat. After that the application stops and asks me to force close it. I initially did some searching and found out that getLatitude and getLongitude return double values. So I corrected the code. But still I am getting an error. What am I doing wrong?
EDIT : The logcat error:
Got RemoteException sending setActive(false) notification to pid 796 uid 10036 I think currentLocation is returning nullIf your are testing your app in the Emulator
you probably don't have any provider and the currentLocation
object is null and that is why getLatitude()
and getLongitude()
will give a NPE.
Edit: as the @grinnner said, from the DDMS perspective you can simulate the sending of location coordinates. Open the DDMS Perspective in eclipse and in the LocationControls tab set the Longitude and Latitude and then click send. Be sure that the focus in the Devices tab is on the emulator that you are running your app on.
If you don't have a last known location (just do a simple null check for the value returned), then you need to add a location listener to get a location. Something like this:
// Start listening for a new location.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String bestProvider = lm.getBestProvider(new Criteria(), true);
mMyLocationListener = new MyLocationListener();
lm.requestLocationUpdates(bestProvider, 0, 0, mMyLocationListener);
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Do what you need to do with the longitude and latitude here.
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You should also remember to remove the location listener as soon as you no longer need it:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(mMyLocationListener);
mMyLocationListener = null;
精彩评论