I have an activity in my app which shows Google Map and there is some other functionality to select the location. The activity is named as MapActivity
and it extends FragmentActivity
.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initializeMap();
}
private void initializeMap() {
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if(mapFragment!=null){
mapFragment.getMapAsync(MapActivity.this);
}
// check if map is created successfully or not
if (null== googleMap) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMyLocationEnabled(true);
}
}
But when this activity is launched the app crashes as it mapFragment object in initializeMap method is returned null. This error has appeared since getMap()
has been deprecated and getMapAsync()
method is to be used but my mapFragment
object it self is null
.
How do inflate the map fragment to avoid this NullPointerException?