Question

null pointer exception when getting android google maps where is the error ?

MapActivity.java :

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map1))
           .getMap();

    Marker marker=map.addMarker(new MarkerOptions().position(LOCATION_CITY).title("").visible(true));
    marker.setDraggable(true);


}

xml file:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name="com.google.android.gms.maps.MapFragment"/>
Was it helpful?

Solution

you should simply check by

if (map != null) {
   Marker marker=map.addMarker(new MarkerOptions().position(LOCATION_CITY).title("").visible(true));
marker.setDraggable(true);
}

Must be sure that if your minimum SDK version is < 12 then you must use

android:name="com.google.android.gms.maps.SupportMapFragment"

and if it is >=12 then you should use this

android:name="com.google.android.gms.maps.MapFragment"

OTHER TIPS

Use SupportMapFragment instead of MapFragment like:

map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map1)).getMap(); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top