mapFragment.getMapAsync(这个) - NullPointerException

mapFragment.getMapAsync(this) - NullPointerException

我正在使用 com.google.android.gms:play-services-maps:7.5.0 版本的 Google 地图服务。当尝试调用下面的内容时,我得到 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 文件:

<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>

您正试图在片段存在之前找到它。您指出具有该片段的布局是 fragment_example_map.xml。但是,您试图在扩充该布局文件之前找到地图片段。这行不通。

除此之外,您似乎正试图从另一个片段内部获取地图片段,使用该片段的 onCreateView() 方法。我不知道你为什么要在这里嵌套片段,因为它似乎会使你的代码更复杂、更脆弱,而且没有明显的好处。

我在带有片段的地图中的评论,首先你应该引用你的视图,因为你会从它调用一些东西,这就是为什么我首先膨胀我的视图
View view = inflater.inflate(R.layout.activity_maps, null, false);

第二次调用子片段管理器 this.getChildFragmentManager() 而不是 getActivity().getSupportFragmentManager()

这是查看地图的完整示例

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));
    }
}

需要权限

<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" />

加上特征元素

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

大部分导入 google 映射键

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

更新 如果你遇到 Error inflating class fragment

添加这个元数据
<meta-data 
      android:name="com.google.android.geo.API_KEY"  
      android:value="your_key_here" />

主要节日的夏天

<?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" />

替换此代码

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

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

    }

在片段中使用 getChildFragmentManager() 代替 getActivity().getSupportFragmentManager()

喜欢:

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

根据 Android 版本或 SDK 版本 5 及更高版本使用 getChildFragmentManager(),低于它使用 getFragmentManager()。

用这个代替 SupportMapFragment:)

 GoogleMap gooleMap;

   ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap map) {
                googleMap = map;
            }
        });

只需在 Activity

中的 onResume 中调用 supportMapFragment.getMapAsync(this);

如果您在片段中使用 android:name="com.google.android.gms.maps.MapFragment",请将您的代码更改为:

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

但是,如果您使用的是 android:name="com.google.android.gms.maps.SupportMapFragment" 在您的片段中然后使用此代码:

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

当您在片段内部使用地图时,getFragmentManager() 可能无法正常工作。你必须使用 getChildFragmentManager().

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

下面是我的 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" />

您还需要在片段中实现 OnMapReadyCallback。

简单的答案是如果你想添加 Map Fragment 这个

<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" />

进入你的片段:喜欢这个布局

 <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>

那么你必须在像这样膨胀片段之后添加这一行

 @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);
.....

进入你的Activity:这样的布局

<?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>

那么你必须添加这段代码。

  @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);
      }

如果我错了请纠正我,但总是在膨胀布局或设置内容视图后添加地图片段。

这对我有用:

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

我正在使用 SupportMapFragment,在 XML 中我定义了 MapFragment name 属性

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

所以我用 SupportMapFragment 替换了代码,它开始正常工作

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

遇到了同样的问题。由于您在 Fragment 中使用 Map 片段,因此请使用 getChildFragmentManager() 而不是 getActivity().getFragmentManager()getFragmentManager().

如果你想在侧面片段中使用地图片段,请使用这个

SupportMapFragment mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.flMap, mMapFragment);
fragmentTransaction.commit();
mMapFragment.getMapAsync(this);

在 onCreate 中尝试此代码

if (mapFragment != null) {
    mapFragment.getMapAsync(this);
}

如果您使用的是 Fragment,请更改此代码

SupportMapFragment mapFragment =getActivity().getSupportFragmentManager().findFragmentById(R.id.map);

supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
  • 还要检查 XML 文件中的更改

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

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