导航抽屉中的谷歌地图 - 空指针异常,哪个是正确的片段?
Posted
技术标签:
【中文标题】导航抽屉中的谷歌地图 - 空指针异常,哪个是正确的片段?【英文标题】:Google Maps in Navigation Drawer - Nullpointer Exception, which is the right Fragment? 【发布时间】:2016-04-24 07:31:44 【问题描述】:我尝试在我的应用中实现 Google 地图。我使用导航抽屉并像这样调用我的片段:
//Main-Class
public void onNavigationDrawerItemSelected(int position)
Fragment myFramgent = null;
switch (position)
...
case 2 :
myFramgent = new Fillilaen();
System.out.println("FILLIAEN");
break;
...
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, myFramgent)
.commit();
Fillialaen 类
public class Fillilaen extends SupportMapFragment implements ...
private GoogleMap mMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
myView = inflater.inflate(R.layout.fillialen2, container, false);
return myView;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.location_map);
fragment.getMapAsync(this); //ERROR COMES HERE
public void onMapReady(GoogleMap googleMap)
//never enter this..
mMap = googleMap;
Marker hamburg = mMap.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg"));
我的 XML
<fragment
android:id="@+id/location_map"
android:layout_
android:layout_
class="com.google.android.gms.maps.SupportMapFragment" />
我得到了一个 NullPointerException,我完全不知道为什么。我搜索了很多并发现了类似的问题,但没有任何帮助。
Nullpointer 异常的开始:
致命异常:主要 进程:roth.com.test6,PID:13097 java.lang.NullPointerException:尝试在空对象引用上调用接口方法“void com.google.maps.api.android.lib6.e.fl.o()” 在 com.google.maps.api.android.lib6.e.y.b(Unknown Source) ....
谢谢!
【问题讨论】:
【参考方案1】:您正在尝试将 SupportMapFragment 嵌套在外部 SupportMapFragment 中。
如果您的 Fragment 扩展了 SupportMapFragment,则无需扩充任何布局 xml,您只需调用 this.getMapAsync()
,因为 this
指的是 SupportMapFragment:
public class MyMapFragment extends SupportMapFragment
implements OnMapReadyCallback
private GoogleMap mMap;
private Marker marker;
public MyMapFragment ()
@Override
public void onResume()
super.onResume();
setUpMapIfNeeded();
private void setUpMapIfNeeded()
if (mMap == null)
//"this" is a SupportMapFragment,
//and "this" implements OnMapReadyCallback
// so you can call this.getMapAsync(this) here:
getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
setUpMap();
private void setUpMap()
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(LatLng point)
//remove previously placed Marker
if (marker != null)
marker.remove();
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
);
【讨论】:
以上是关于导航抽屉中的谷歌地图 - 空指针异常,哪个是正确的片段?的主要内容,如果未能解决你的问题,请参考以下文章