Search code examples
javaandroideclipsegoogle-maps-android-api-2google-maps-api-2

Showing google maps in activity (not MainActivity)


I'd like to show a google map in my Android application. I found en example which was tested by me by putting it in the main activity. This works without any problems. To improve my app I'd now like to outsource the map in another activity (called DisplayMapActivity). When the button "Show map" is clicked, the map activity is called. But my app crashes and I get a nullpointer exception.

My project is example.com.lbsapp2 and here is some code:

MainActivity.java:

public void openMap(View view) {
    Intent intent = new Intent(this, DisplayMapActivity.class);
    startActivity(intent);
}

This is called when clicking on the button. It should open the map.

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

This has worked in MainActivity.java without any problems so the code should be okay.

activity_display_map.xml (Layout):

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

This was in activity_main.xml before and has worked fine.

The manifest should be okay as well as it had worked before.


Solution

  • In DisplayMapActivity change this

    setContentView(R.layout.activity_main);
    

    to

    setContentView(R.layout.activity_display_map);
    

    cause MapFramgent is in activity_display_map.xml.

    Also getMap() could return null. So check the availability of google play services before initialize GoogleMap object