0

In my application i'm using navigation drawer with swipe tabs (following this) and inside one of these tabs i want to use google maps. I'm getting this error:

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

I've searched and discovered that i can only call getMapAsync() on the main thread. However nearly all the solutions i faced were using deprecated methods. How can I initialise the map,to avoid the null exception, and only call it on this tab?

My Tab Fragment

public class PrimaryFragment extends Fragment implements OnMapReadyCallback {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.primary_layout,container,false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    SupportMapFragment supportMapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    supportMapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    //toDO
}

}

The tab fragment xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    class="com.google.android.gms.maps.SupportMapFragment"/>

</FrameLayout>
Artur Galdino
  • 103
  • 1
  • 1
  • 5

1 Answers1

0

You can replace this line --

SupportMapFragment supportMapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));

to this --

SupportMapFragment supportMapFragment = ((SupportMapFragment) view.getChildFragmentManager().findFragmentById(R.id.map));

Hope this helps!

Saumik Bhattacharya
  • 891
  • 1
  • 12
  • 28