Sebastian Martinez
Sebastian Martinez

Reputation: 1

I'm getting GoogleMap.clear on a null object reference

I have a Google Maps based application and it was working with the methods getMap(), now with the new model getMapAsync, I'm having troubles when I want to clear or use in general the GoogleMap object,

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.clear()' on a null object reference.

I'm using a Fragment.

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_passenger_page1,
                container, false);
        MapFragment fm = (MapFragment) mainActivity.getFragmentManager().findFragmentById(R.id.map);
        fm.getMapAsync(this);
...
}

the problem is here when I use:

   @Override
    public void onResume() {

mMap.clear();

        if (listMarkers.size() > 0)

        {
            setMarker(listMarkers);
        }
        super.onResume();

    }

This function is called every time the App opens, and says that mMap is null.

Please help me.

Upvotes: 0

Views: 742

Answers (2)

Sebastian Martinez
Sebastian Martinez

Reputation: 1

thanks for your comments, I solved my problem by calling a clear() function in onResume, checking if the GoogleMap exists and if not creating it and passing to mMap.

 @Override
public void onResume() {

    clear();
    if (listMarkers.size() > 0)

    {
        setMarker(listMarkers);
    }
    super.onResume();

}

The clear function looks like:

public void clear() {

    GoogleMap gm = createMap();
    if (gm == null) {
        Log.e("clear", "The map is null"); //for testing purposes
        return;

    } else {
        Log.e("clear", "The map already exists"); //for testing purposes
        mMap = gm;
        mMap.clear();
    }


    startLocation = null;
    endLocation = null;
    txtFrom.setText("");
    txtTo.setText("");

}

And finally the createMap():

 private GoogleMap createMap() {

    if (mMap != null) {
        Log.e("create", "The map already exists"); // for testing purposes
        return mMap;
    }
    MapFragment fm = (MapFragment) 
    mainActivity.getFragmentManager().findFragmentById(R.id.map);
    try {
        fm.getMapAsync(this);
    } catch (Exception ex) {
        Log.e("Error", ex.getLocalizedMessage());
    }

    return null;

}

So in this way I always create a new GoogleMap if it doesn't exists.

If i'm doing something wrong don't hesitate to tell me :)

Upvotes: 0

umesh shakya
umesh shakya

Reputation: 237

please implement OnMapReadyCallback interface and override

 @Override
 public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    googleMap.clear()
    if (listMarkers.size() > 0)

    {
        setMarker(listMarkers);
    }


 }

and remove code from on resume methods

Upvotes: 1

Related Questions