mapFragment.getMapAsync(this) - NullPointerException [英] mapFragment.getMapAsync(this) - NullPointerException
问题描述
我使用 com.google.android.gms:play-services-maps:7.5.0
版Google地图服务。当试图调用下面的代码时,我得到 java.lang.NullPointerException:尝试调用虚方法void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps .OnRide
。
public View onCreateView
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文件:
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>
推荐答案
您试图在存在片段之前找到片段。您指出具有该片段的布局是 fragment_example_map.xml
。但是,您正在尝试在膨胀该布局文件之前查找地图片段。这是行不通的。
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.
除此之外,您似乎试图从另一个片段中获取地图片段,该片段的 onCreateView( )
方法。我不知道为什么你要在这里嵌入片段,因为它看起来会让你的代码更复杂,更脆弱,没有明显的好处。
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.
这篇关于mapFragment.getMapAsync(this) - NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!