我正在尝试获取 fragment 中 onCreateView() 中的当前位置。我在尝试获取当前经度的行上遇到空指针异常。我做错了什么?
final LocationListener locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location currentLocation)
{
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
最佳答案
你没有看错。
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
该方法仅返回最后已知位置。它不计算位置。当没有旧位置记录时,它将为空。您请求更新代码。因此,如果您需要,您可以等到获得位置更新为止。
关于java - NullPointerException Location.getLongitude(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471882/