-1

my code is throwing null pointer error and crashing the complete app. I have checked with button id its correct but cannot find an error. I m trying to allocate this function to a button. Basically i want to access current location latitude longitude and display a marker over there. So if u have any alternate code also it will do

 public void onPing(View view) {
    if (view.getId() == R.id.button2) {
        mMap.clear();
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        subLoc = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(subLoc).title("Current Position"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(subLoc));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243

1 Answers1

1

Location from lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); could be null.

 if(location != null){
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        subLoc = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(subLoc).title("Current Position"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(subLoc));
 }
Ravi Theja
  • 3,371
  • 1
  • 22
  • 34