1

I am trying to get the location of the user from location api of android. I have written following lines of code to get the latitude and longitude and then send the data to some other activity via Intent.

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10f, this);

    Criteria criteria = new Criteria();

    String provider = locationManager.getBestProvider(criteria, true);

     location = locationManager.getLastKnownLocation(provider);

    try{
        latitude = location.getLatitude();

        longitude = location.getLongitude();

        LatLng latLng = new LatLng(latitude, longitude);

        myPosition = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(myPosition));
    }catch (NullPointerException e){
        e.printStackTrace();
    }

But I got 1 error, when I run on android 5+ device I get Null pointer Exception on each line from getting latitude variable. But for other android sdks Null pointer exception does not appear also.

And also the marker is not visible So I think this is the where NPE comes into picture. But I don't know why android 5+ gives this behaviour. I have compiled this app using android 6.

So for this purpose I have written code in try catch block and added NPE.

Why this is causing error? I am not able to figure it out. Thanks in advance!!

0 Answers0