2
I have the following code which returns NullPointerException on the line: lat = location.getLatitude();
private GoogleMap mMap;
private String provider;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double lat =0;
double lng =0;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//mMap.addMarker(new MarkerOptions().position(new LatLng(21.000,-51.000)));
mMap.setMyLocationEnabled(true);
Criteria criteria = new Criteria();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(criteria,false);
if (provider != null){
Location location = locationManager.getLastKnownLocation(provider);
lat = location.getLatitude();
lng = location.getLongitude();
onLocationChanged(location);
}else{
Toast.makeText(this,"Perdemos Você",Toast.LENGTH_LONG).show();
}
}
Detail am using Android Studio!
– Balrog
That one
onLocationChanged()by chance it means that your Activity is implementingLocationListener? Because if it is, the goal is not to call it explicitly but to wait for the GPS to get a new position and call this method without you having to do it (note: this will only happen if before that you callrequestLocationUpdates()). This is how you get new positions. The methodgetLastKnownLocation()only returns the last position obtained that way I spoke, before that it returns nothing even.– Piovezan
yes implement Locationlistener! Thank you very much for the tip! ñ had analyzed this possibility.
– Balrog