Android纬度和经度返回null

问题描述:

我得到一个奇怪的错误,因为如果我在真实的手机上运行该应用程序,它不会给出此错误(Android 5.0)。但是,在模拟器上(安卓6.0),它给了我这个错误:Android纬度和经度返回null

FATAL EXCEPTION: main Process: com.doppler.stackingcoder.pechhulp, PID: 11424 java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onLocationChanged(PechhulpActivity.java:171) at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onMapReady(PechhulpActivity.java:126)

这是我PechhulpActivity:

https://gist.github.com/soufyanekaddouri/6e3a3746be137e2680caa32d7bb746d9

我希望有人知道我做错了。

对于您的崩溃,您假设至少有一个提供商将从getLastKnownLocation()返回Location。这不是必需的,无论是设备还是仿真器。您需要处理所有提供商从getLastKnownLocation()返回null的情况。这可以通过不尝试使用该位置。或者,请求位置更新,然后使用第一次更新中的位置。

+0

你有我的例子吗?我只是一个初学者 – Stackingcoder

+0

@Stackingcoder:那么,我有[这个示例](https://github.com/commonsguy/cw-omnibus/tree/master/WebKit/GeoWeb2),请求位置更新,并尝试使用' getLastKnownLocation()',尽管这个例子与使用'WebView'的东西绑定在一起。我有[此示例](https://github.com/commonsguy/cw-omnibus/tree/master/Internet/Weather)这是一个更传统的应用程序,但只请求(和使用)位置更新。 – CommonsWare