I have an app that pinpoints the users location on a map. This runs successfully on both my Nexus 4 & 5, but will no longer work on my Nexus 7.
It did run on the 7, but then the device powered off during execution, and now the app will no longer work.
I have reset the device back to factory and have run all updates on it.
Here is the code from my onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate center = CameraUpdateFactory.newLatLng(coordinate);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
map.moveCamera(center);
map.animateCamera(zoom);
}
It says that I am getting a NullPointerException at ** ** double lat = location.getLatitude();
I could understand an issue if it would happen on all my devices, but I can't wrap my head around why just this one device (and especially after it worked earlier)?
Per the getLastKnownLocation documentation:
If the provider is currently disabled, null is returned.
as you are using getBestProvider(criteria, false)
you are saying you allow providers that are not enabled (that's what false
means) - switch it to true
if you only want to look at enabled providers (which will assure that getLastKnownLocation does not return null).
Note that the getLastKnownLocation
could be very out of date and you may still want to look for location updates if you need to get a recent location.