Question

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)?

Was it helpful?

Solution

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.

OTHER TIPS

There are a couple things to keep in mind when deling with gsp or network location.

*- The data takes time to arrive to your device: yes , it may take even 1 minute to recive the device 's current location. Thats why you should use a LocationListener

*-May sounds crazy but verify your smartphone is connectecd to the internet

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top