java - NullPointerException Location.getLongitude()

标签 java android location android-location

我正在尝试获取 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/

相关文章:

android - 是否可以通过编程方式将 BluetoothDevice 与 android 配对?

java - 使用 LocationListener 的 BlackBerry 应用程序在 OS 6 上卡住

android - 显示允许应用访问设备的位置

java - JLabel:异步加载 HTML 图像

android - 为什么 Android Studio 不允许我创建 Java 类?

java - Heroku Hobby Plan 的 slug 大小限制是多少?

java - Android - Future.get() 使 UI 卡住

ios - 如何让应用程序根据用户移动的距离更新服务器?

java - RxJava迭代对象中的列表并返回对象

java 按键方法调用