MapFragment.getMapAsync ( this) - NullPointerException


Estoy usando com.google.android.gms:play-services-maps:7.5.0 la versión de los servicios de Google Maps. Al intentar llamar a la siguiente obtengo 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.archivo xml:

<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>
Author: Neutrino, 2015-06-23

13 answers

Estás intentando encontrar un fragmento antes de que exista. Indica que el layout que tiene el fragmento es fragment_example_map.xml. Sin embargo, está tratando de encontrar el fragmento de mapa antes de inflar ese archivo de diseño. Esto no funcionará.

Más allá de eso, parece que estás tratando de llegar al fragmento del mapa desde dentro de otro fragmento, en el método onCreateView() de ese fragmento. No sé por qué están anidando fragmentos aquí, ya que parece que hará que su código sea más complejo y más frágil para no beneficio obvio.

 8
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-22 22:52:53

Mi comentario en mapas con fragmento, primero debes refrenece tu vista ya que llamarás a algo de ella, es por eso que inflo mi vista primero
View view = inflater.inflate(R.layout.activity_maps, null, false);

Administrador de fragmentos secundarios de segunda llamada this.getChildFragmentManager() en lugar de getActivity().getSupportFragmentManager()

Aquí está el ejemplo completo para ver el mapa

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class ClinicFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;

    public static ClinicFragment newInstance() {
        ClinicFragment fragment = new ClinicFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_maps, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        return view;
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

Permiso requerido

<permission
    android:name="your.package.name.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />
<uses-permission android:name="your.package.name.permission.MAPS_RECEIVE"/>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Más elemento de característica

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

Más importación clave de google maps

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="your_key_here" />

Update añadir este meta data if you face Error inflando fragmento de clase

<meta-data 
      android:name="com.google.android.geo.API_KEY"  
      android:value="your_key_here" />

Verano para el mainfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name" >
// permission here

 <application
        android:name=".Activities.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

    // feature element 
    // maps key

  </application>

</manifest>

Activity_maps.xml

<fragment 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.imaadv.leaynik.ClinicFragment" />
 109
Author: Mina Fawzy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:48

Use getChildFragmentManager() en lugar de getActivity().getSupportFragmentManager() en el fragmento.

Como:

SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this); 
 14
Author: Arun kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-16 13:01:44

Si estás usando android:name="com.google.android.gms.maps.MapFragment" en tu fragmento entonces cambia tu código con:

MapFragment mapFragment1 = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
        mapFragment1.getMapAsync(this);

Sin embargo, si está utilizando android:name="com.google.android.gms.maps.SupportMapFragment" en tu fragmento usa este código:

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
 7
Author: Nagendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-21 10:27:18

Esto funciona para mí:

SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this); 
 5
Author: Rayan Teixeira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 03:37:48

Dependiendo de la versión de Android o SDK versión 5 y superior use getChildFragmentManager() y por debajo usó getFragmentManager().

 2
Author: jan_013069,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 07:55:20

Use esto.

GoogleMap gooleMap;

     ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap map) {
            googleMap = map;
           }
 1
Author: Harsh Bhavsar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 05:36:51

Es posible que getFragmentManager() no funcione cuando esté usando map inside fragment. Tienes que usar getChildFragmentManager () .

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_track_order_map_fragment);
mapFragment.getMapAsync(this);

Y a continuación está mi declaración xml

<fragment
    android:id="@+id/fragment_track_order_map_fragment"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

También necesitas implementar OnMapReadyCallback en tu fragmento .

 1
Author: varotariya vajsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-01 15:28:10

La respuesta simple es si desea agregar un fragmento de mapa,

<fragment 
    xmlns:android="http://schemas.android.com/apk/res/android"
    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:layout="@layout/fragment_home" />

En tu fragmento: como este diseño

 <android.support.constraint.ConstraintLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="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.android.earthreport.fragments.HomeFragment"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="81dp">

     <fragment 
xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="@id/guideline4"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@id/guideline3"
            tools:layout="@layout/fragment_home" />
        </android.support.constraint.ConstraintLayout>

Entonces tienes que añadir esta línea después de inflar el fragmento de esta manera

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

        // Find a reference to the {@link ListView} in the layout
        // Inflate the layout for this fragment
        // To get the referance we don't have findviewbyId 
        // method in fragment so we use view
        View view = inflater.inflate(R.layout.fragment_home, container, false);


          SupportMapFragment mapFragment = (SupportMapFragment) 
                  this.getChildFragmentManager()
                  .findFragmentById(R.id.map)
          mapFragment.getMapAsync(this);
.....

En tu actividad: como este diseño

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:context="package com.example.android.map" />

</android.support.constraint.ConstraintLayout>

Entonces tienes que añadir este trozo de código.

  @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
      }

Corríjame si me equivoco, pero siempre agregue un fragmento de mapa después de inflar el diseño o establecer la vista de contenido.

 1
Author: badarshahzad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-20 04:32:54

Reemplace este código

<fragment 
    android:name="com.google.android.gms.maps.MapFragment"
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="400dp" />

Y

if (googleMap == null) {
        mapFrag =  (MapFragment)getFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }else{
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    }
 0
Author: Mujtaba Zaidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-11 05:29:34

Simplemente Llama a supportMapFragment.getMapAsync(this); en onResume en tu Actividad

 0
Author: fanjavaid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 10:21:25

Estaba usando SupportMapFragment y en XML definí MapFragment name attribute

android:name="com.google.android.gms.maps.MapFragment"

Así que reemplacé el código con SupportMapFragment y comenzó a funcionar bien

android:name="com.google.android.gms.maps.SupportMapFragment"
 0
Author: Naveed Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-30 05:26:21

Se enfrentó al mismo problema. Dado que está utilizando el fragmento de mapa dentro de un fragmento, use getChildFragmentManager () en lugar de getActivity ().getFragmentManager () o getFragmentManager ()

 0
Author: Devenom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 13:29:00