I am using com.google.android.gms:play-services-maps:7.5.0
version of Google Maps services. When trying to call the below I get 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
.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); //error
return inflater.inflate(R.layout.fragment_example_map, container, false);
}
fragment_example_map.xml file:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.ExampleMap">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
use this.
You are attempting to find a fragment before it exists. You indicate that the layout that has the fragment is
fragment_example_map.xml
. However, you are trying to find the map fragment before you inflate that layout file. This will not work.Beyond that, you appear to be trying to get at the map fragment from inside another fragment, in that fragment's
onCreateView()
method. I do not know why you are nesting fragments here, as it seems like it will make your code more complex and more fragile for no obvious benefit.My comment in maps with fragment , first you should refrenece your view as you will call something from it , this is why I inflate my view first
View view = inflater.inflate(R.layout.activity_maps, null, false);
Second call child fragment manager
this.getChildFragmentManager()
instead ofgetActivity().getSupportFragmentManager()
Here is the full example to view map
required permission
plus feature element
most import google maps key
Update add this meta data if you face Error inflating class fragment
summery for mainfest
activity_maps.xml
this works for me:
replace this code
and
If your are using
android:name="com.google.android.gms.maps.MapFragment"
in your fragment then change your code with:However if your are using
android:name="com.google.android.gms.maps.SupportMapFragment"
in your fragment then use this code: