-2

I have been working on google maps and below is the method I am using to initialize the map. Surprisingly, mapFragment.getMapAsync() method is not getting executed so googleMaps object is still null after calling getMapAsync().

// Initialize the google map

void initMap() {
    Log.d(MAPSACTIVITY_TAG, "Initializing google map");
    mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.maps_fragment);
    mapFragment.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap gMap) {
            Log.d(MAPSACTIVITY_TAG,"Maps is ready");
            googleMap=gMap;
        }
    });

    Log.d(MAPSACTIVITY_TAG,"Value of google maps is "+googleMap);

    //This will get device location, set GoogleAPIClient and set mundu marker
    if (isLocationPermissionGranted) {
        getDeviceLocation();
        buildGoogleApiClient();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "Sorry! App requires location permission", Toast.LENGTH_SHORT).show();
            return;
        }
        googleMap.setMyLocationEnabled(true);
        //this will get client's location and set client's marker
        geoLocateClient();
    } else
        Log.d(MAPSACTIVITY_TAG, "Location permission is not given");
}

Here is the Logcat snapshot:enter image description here

Please notice, Log statement in the getMapAsync is never executed. Can anyone help me with this?

Edit:

Someone marked this question as a duplicate of What is a NullPointerException, and how do I fix it? Please notice this question is about how and when onMapReady() method is called by getMapAync() (its nothing related to the null pointer exception)

Community
  • 1
  • 1
Wijay Sharma
  • 439
  • 7
  • 17

1 Answers1

2

You should move code that uses variable googleMap inside onMapReady(...) { ... } method because getMapAsync(...) is asynchronous and onMapReady(...) will be called later in a different thread after Maps has responded.

haba713
  • 2,465
  • 1
  • 24
  • 45
  • it looks like onMapReady() is never called. See the Log statement. Its never shown in the output. – Wijay Sharma Jan 12 '18 at 20:46
  • 1
    Your code tries to access the variable `googleMap` before Google Maps reponds and `onMapReady` is called. See the tutorial [1] for more information. All the map handling is inside `onMapReady(...) { ... }` method. [1] https://github.com/googlemaps/android-samples/blob/master/tutorials/CurrentPlaceDetailsOnMap/app/src/main/java/com/example/currentplacedetailsonmap/MapsActivityCurrentPlace.java#L146 – haba713 Jan 12 '18 at 21:05