java.lang.NullPointerException about gps api?
as the title i have a question about the gps api follow is my code
LocationManager loctionManager;
String contextService=Context.LOCATION_SERVICE;
loctionManager=(LocationManager) getSystemService(contextService);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER开发者_JAVA技巧_LOW);
String provider = loctionManager.getBestProvider(criteria, true);
Location location = loctionManager.getLastKnownLocation(provider);
double a=location.getLatitude();
double b=location.getLongitude();
Log.d(""+a,""+b);
then the error is java.lang.NullPointerException anyone can help me?thx
getLastKnownLocation()
can return null you need to ensure it does not.
In order to get a Location you need at first to set permission in your Manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then in your code you need to listen for location avalability. You do that by registering a LocationListener
. The activity will display, and when Android will have a location for you it will call you back.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
//Do what you want with your coordinates
}
loctionManager.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener);
If you are using the emulator and not a real device you need to force a location, you can use DDMS inside Eclipse to send a fake location:
精彩评论