Soufyane Kaddouri
Soufyane Kaddouri

Reputation: 333

Android latitude and longitude returns null

I am getting a strange error because if I run the app on a real phone, it doesn't give this error (Android 5.0) . But on the emulator (Android 6.0) it gives me this error:

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)

And this is my PechhulpActivity:

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

Upvotes: 1

Views: 95

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

With respect to your crash, you are assuming that at least one provider will return a Location from getLastKnownLocation(). That is not required, on either a device or an emulator. You need to handle the case where all providers return null from getLastKnownLocation(). This could be by not attempting to use the location. Or, requests location updates, then use the location from the first update.

Upvotes: 1

Related Questions