mapFragment.getMapAsync (this) – NullPointerException
Estoy usando com.google.android.gms:play-services-maps:7.5.0
versión com.google.android.gms:play-services-maps:7.5.0
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); }
archivo fragment_example_map.xml:
- MapView - Android
- Android OnInfoWindowClickListener () nunca llamado
- Marcadores personalizados que muestran con color blanco en algunos dispositivos (Google Maps v3 Android SDK)
- Azulejos personalizados borrosos en Android Maps V2
- GoogleMap necesita activación?
<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>
- Fragmento de Google Maps devolviendo nulo dentro de un fragmento
- Especificación de XML adicional para AndroidManifest generado por gradle
- ¿Cómo crear un enlace para todos los dispositivos móviles que abre google maps con una ruta que empieza en la ubicación actual, destinando un lugar determinado?
- Android, google maps fragment y viewpager - Error al inflar el fragmento de clase
- Detectar si el usuario "anula la selección" del marcador en el mapa de google
- Cómo agregar botones en la parte superior del fragmento de mapa Diseño API v2
- Poner a los marcadores de Google Map al frente cambiando el índice Z en Android
- Mi superposición no aparece hasta que se pulse mapView en android
Está intentando encontrar un fragmento antes de que exista. Indica que el diseño que tiene el fragmento es fragment_example_map.xml
. Sin embargo, está intentando encontrar el fragmento de mapa antes de inflar ese archivo de diseño. Esto no funcionará.
Aparte de eso, parece que está tratando de obtener el fragmento de mapa de dentro de otro fragmento, en el método onCreateView()
ese fragmento. No sé por qué estás anidando fragmentos aquí, ya que parece que hará que tu código sea más complejo y más frágil para ningún beneficio obvio.
Mi comentario en los mapas con el fragmento, primero debe refrenece su punto de vista, ya que llamará a algo de ella, es por eso que inflar mi opinión primero
View view = inflater.inflate(R.layout.activity_maps, null, false);
Administrador de fragmentos hijo de segunda llamada this.getChildFragmentManager()
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" />
elemento más elemento
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
la mayoría de importar google maps clave
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_key_here" />
Actualizar agrega estos metadatos si te enfrentas Error al inflar fragmento de clase
<meta-data android:name="com.google.android.geo.API_KEY" android:value="your_key_here" />
summery 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" />
use getChildFragmentManager()
en lugar de getActivity().getSupportFragmentManager()
en el fragmento.
me gusta:
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this);
Si estás utilizando android:name="com.google.android.gms.maps.MapFragment"
en tu fragmento, entonces cambia tu código por:
MapFragment mapFragment1 = (MapFragment)getFragmentManager().findFragmentById(R.id.map); mapFragment1.getMapAsync(this);
Sin embargo, si estás usando android:name="com.google.android.gms.maps.SupportMapFragment"
en tu fragmento entonces usa este código:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this);
Dependiendo de la versión de Android o SDK versión 5 y superior use getChildFragmentManager () y por debajo usó getFragmentManager ().
reemplazar 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); }
utilizar esta.
GoogleMap gooleMap; ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap map) { googleMap = map; }
Sólo supportMapFragment.getMapAsync(this);
llamar a supportMapFragment.getMapAsync(this);
in onResume
en su actividad
- Cómo obtener información del dispositivo en Android
- ¿Cómo evitar el reajuste total de la jerarquía de vista cuando se utiliza EditText?