i am trying to get current location latitude and longitude using the code below but it开发者_如何学C force close and display in log cat "null pointer exception
" so pls check where i am wrong..my cod is below...
I think that if the null pointer exception really happens within the if()
block, at the getLatitude()
call, this means the reference to the Location object that you just tested is no longer valid.
So I would try to copy the location object before using it, like this:
public void onLocationChanged(Location location) {
Location copyOfLocation = new Location(location);
updateWithNewLocation(copyOfLocation );
}
Haven't tested this, and I don't remember seeing this problem before...
--Edit--
Wait, the exception has moved since your last edit... Well your location is null probably because the system has no previous location to give you. Try going outside with your phone, power on the GPS, launch Google Maps until the GPS icon in the notification bar does not blink anymore, quit Maps, go back inside and try your app again.
-- Edit 2--
There are two conditions for getLastKnownLocation to work:
- the location provider must be powered on (must use the Android preferences panel to turn the GPS on)
- the system must have computed a position with the required provider sometime in the past
Else it will return null
精彩评论