2017-04-04 49 views
-3

我在我的应用程序中显示Google Map的活动,还有一些其他功能可以选择位置。该活动被命名为MapActivity,它扩展为FragmentActivityMapFragment中的NullPointerException;谷歌地图在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

https://developers.google.com/maps/documentation/android-api/start –

回答

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)); 
    } 
} 
+0

https://developers.google.com/maps/documentation/android-api/start –

+0

感谢快速的回应。我浏览了链接并将代码从MapFragment更改为SupportMapFragment。但是现在我的onMapReady方法没有被调用,因为我的googleMap对象为null。 –

+0

你是否声明了清单中的权限? – AwaisMajeed

相关问题