androidandroid-fragmentsandroid-mapviewandroid-fragmentactivitymapactivity

How to show GoogleMap inside ConstraintLayout?


I created a new project "MapsActivity". I got my API key from Google, placed the API key in google_maps_API.xml(debug) inside the YOUR_KEY_HERE area. I see in AndroidManifest it's there. Then I go to build/run the app and it crashes.

I didn't even code anything yet.

According to Android Monitor here's the crash report:

 Caused by: 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
                                                 at com.example.mikedouglas.maps.MapsActivity.onCreate(MapsActivity.java:24)

So I click on the MapsActivity.java:24 and it takes me to the following:

[![enter image description here][1]][1]

Remember, I didn't touch any code yet, just created this new project, only added the API key where I was supposed to and clicked build/run and then it crashes. This is all Google created code that crashes.

I looked on StackOverflow and tried changing from getSupportFragmentManager to getChildFragmentManager as people say and it doesn't work.

activity_maps.xml file:

<android.support.constraint.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mikedouglas.maps.MapsActivity" />

What's wrong? What do I have to change?

EDIT:

A tag allows a layout file to dynamically include different layouts at runtime. At layout editing time the specific layout be used is no known. You can choose which layout you would like previewed while editing the layout.


Solution

  • You need to put the Fragment inside the ConstraintLayout:

    <android.support.constraint.ConstraintLayout      
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mikedouglas.maps.MapsActivity">
    
        <fragment
            android:id="@+id/map"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </android.support.constraint.ConstraintLayout>