【发布时间】:2015-09-15 01:55:24
【问题描述】:
我正在尝试在片段中显示 地图,但我总是得到这个 NullPointerException:
java.lang.NullPointerException:尝试调用虚拟方法 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' 为空 对象引用
我知道在这种情况下这个例外有很多问题,但我找不到我的错误。我阅读了我找到的任何答案。
这是我的代码:
public class DetailKarteFragment extends Fragment {
GoogleMap map;
static final LatLng brend = new LatLng(48.079, 8.157);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_detail_karte, null, false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment fmap = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (fmap == null) {
fmap = SupportMapFragment.newInstance();
ft.add(R.id.map, fmap);
}
ft.commit();
Marker brendMarker = map.addMarker(new MarkerOptions().position(brend).title("Brend"));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(brend, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
和xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/background"
android:layout_height="match_parent">
<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="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Route anzeigen"
android:id="@+id/button_route_planen"
android:layout_gravity="center_horizontal"
android:height="48dp"
android:background="@color/secondary_100"
android:layout_marginBottom="-48dp"/>
</LinearLayout>
</LinearLayout>
【问题讨论】:
标签: java android android-fragments nullpointerexception