Android SupportMapFragment.getMap() returns null

大憨熊 提交于 2019-11-30 20:05:23

问题


in my following code, getMap() returns null, which stop the app. If I don't do anything with the map (i.e, removing the last two lines), it shows correctly. Any idea why? Thanks.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
        mapFragmentId = mapFragment.getId();
        FragmentTransaction transaction =  fragmentManager.beginTransaction();
        transaction.add(R.id.my_container, mapFragment);
        transaction.commit();

        mMap = mapFragment.getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    }

回答1:


Duplicate of: SupportMapFragment.getmap() returns null

Check your layout xml file. I noticed that I wasn't referencing: android:name="com.google.android.gms.maps.SupportMapFragment" but rather: android:name="com.google.android.gms.maps.MapFragment"

The name should be: android:name="com.google.android.gms.maps.SupportMapFragment"




回答2:


If getMap() is returning null it's because Map isn't ready yet or GooglePlayServices is out to date. You better use something like that :

int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(resultCode != ConnectionResult.SUCCESS)
        {
            Builder builder = new AlertDialog.Builder(Main.this);
            builder.setMessage(getResources().getString(R.string.error_getting_maps));
            builder.setCancelable(true);
            builder.setPositiveButton("OK", null);
            AlertDialog dialog = builder.create();
            dialog.show();
        } else {
            _map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            [ETC]
        }


来源:https://stackoverflow.com/questions/18594694/android-supportmapfragment-getmap-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!