我想在我的Android应用程序中显示一个Google地图。我找到了一个示例,并通过将其放入主要活动中进行了测试。这可以正常工作。为了改善我的应用程序,我现在想在另一个活动(称为DisplayMapActivity)中外包地图。单击“显示地图”按钮时,将调用地图活动。但是我的应用程序崩溃了,并且我得到了一个空指针异常。
我的项目是example.com.lbsapp2,下面是一些代码:
MainActivity.java:
public void openMap(View view) {
Intent intent = new Intent(this, DisplayMapActivity.class);
startActivity(intent);
}
单击该按钮时将调用它。它应该打开地图。
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lbsapp2.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml:
<LinearLayout 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"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="openMap"
android:text="@string/button_map" />
</LinearLayout>
DisplayMapActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
这已经在MainActivity.java中正常工作了,所以代码应该没问题。
activity_display_map.xml(布局):
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
这之前在activity_main.xml中,并且运行良好。
清单应该像以前一样正常。
在DisplayMapActivity
改变这个
setContentView(R.layout.activity_main);
至
setContentView(R.layout.activity_display_map);
原因MapFramgent
在activity_display_map.xml
。
也getMap()
可以返回null。因此,请在初始化GoogleMap
对象之前检查Google Play服务的可用性
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句