我的应用中有一项活动,其中显示了Google地图,还有一些其他功能可供选择。该活动名为MapActivity
,并扩展为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);
}
}
但是当启动此活动时,应用程序崩溃,因为它在initializeMap方法中的mapFragment对象返回null。由于getMap()
已被弃用且getMapAsync()
方法被使用,但我自己的mapFragment
对象为null
,因此出现此错误。
如何对地图片段进行充气以避免此NullPointerException?
答案 0 :(得分:0)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}