how to solve Null pointer exception on Getting latitude or GPS?
I am trying to get current long, lat. I am getting a Nullpointer on LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener myLocationListener = new CurrentLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener);
Location currentLocation = locationManager.getLastKnownLocation("gps");
Latitude = currentLocation.getLatitude(); ----->>> null pointer exception here
Longitude = currentLocation.getLongitude();
public class CurrentLocationListener implements LocationListener{
public void onLocationChanged(Location argLocation) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle arg2) {
}
}
My manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
This is usually because there's no last know location. To force obtaining the location you can register for location updates and wait or you can launch google maps application, obtain the location using Menu -> My Location, return to your application and last know location shouldn't be null.
Did you set the right permissions in the manifest file? Something like:
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Kind of obvious ...
Location currentLocation = locationManager.getLastKnownLocation("gps");
if (currentLocation != null)
{
Latitude = currentLocation.getLatitude();
Longitude = currentLocation.getLongitude();
}
Now, about WHY locationManager is returning a null references instead of an actual Location reference ... It's difficult to know with the code provided. Could be anything.
Edit: Mmm, seems like it could be that you have no gps fix yet.
链接地址: http://www.djcxy.com/p/90646.html上一篇: 如何在Android中的onMapReady()之外添加Google地图标记?
下一篇: 如何解决获取纬度或GPS空指针异常?