1

I was following a tutorial and trying to get my current location using Google maps but I am getting an error at LatLng, it says that 'attempt to invoke virtual method and a null object reference'. I want to get my current location and also get latitude and longitude as strings. I am wanna use these latitude and longitude for live location tracking.

public class DriverCurrentLocationActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    updateMap(lastKnownLocation);

                }

            }
        }
    }

    public void updateMap(Location location) {
        try {

            LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.clear();
            mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
            mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
        }catch (Exception e){
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver_current_location);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateMap(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if (Build.VERSION.SDK_INT < 23) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);



        }else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (lastKnownLocation != null){
                    updateMap(lastKnownLocation);
                }
            }
        }
    }
}

2 Answers2

0

Check for null on your updateMap function, since getLastKnownLocation may return null sometimes, that way you won't get a crash or exception. Also try this instead.

Mehmet Katircioglu
  • 1,200
  • 1
  • 11
  • 20
0

create someMethod() in onCreate

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
        fetchLastLocation();

 private void someMethod() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
    Task<Location> task = fusedLocationProviderClient.getLastLocation();
    task.addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {

            if (location != null){
                currentLocation = location;
                Toast.makeText(this,currentLocation.getLatitude() +""+ currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
                SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
                mapFragment.getMapAsync(MapFragment.this);
            }
        }
    });
}

Then in your onMapReady() method use this code:

 LatLng center = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions().position(center).title(center.latitude + ":" + center.longitude);
    mMap.clear();
    googleMap.animateCamera(CameraUpdateFactory.newLatLng(center));
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(center, 18));
    googleMap.addMarker(markerOptions);

Converting LatLng to String:

String string_latlng = center.toString();

hope this will help you :)

Mrunal
  • 578
  • 2
  • 21
  • 39