【问题标题】:Lack of GPS accuracy resulting in null pointer [duplicate]缺乏 GPS 精度导致空指针 [重复]
【发布时间】:2017-02-11 22:47:28
【问题描述】:

ACCESS_COARSE_LOCATION 和 ACCESS_FINE_LOCATON 都已包含在清单中。活动中还包括:

import android.location.Location;
import android.location.LocationManager;

我有一个用于导航抽屉的监听器,具有以下类

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null)
        {
            final double longitude = location.getLongitude();
            final double latitude = location.getLatitude();
        }

    selectItem(position);
    }
}

由此,location = null 将在 location.getLongitude(); 上失败。我当然可以用if (location != null) 避免这种情况,但我希望找到latlong

为什么位置总是空的?

【问题讨论】:

标签: java android nullpointerexception android-location locationmanager


【解决方案1】:

在硬件方面找到位置并不是一件容易的事。你无法告诉设备我想知道我的位置,所以现在就给我!如果在外面清晰可见,它需要观察来自 GPS 卫星的一些数据,否则它会使用其他可用选项,如 wifi。在您的设备找到有效位置之前,您应该等待。我建议您观察onLocationChanged 事件并在此事件发生时更新您的列表视图。在检测到您的位置之前,最好使用null 条件。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 2014-04-02
  • 1970-01-01
相关资源
最近更新 更多