Google map v2 android method getMap() returns null

若如初见. 提交于 2019-12-11 05:38:38

问题


In my application I am using google map programmatically, but when I call getMap() it returns null. even I have tried onActivityCreated() but still it returns null. somebody please help me.. Here is my code,

public void callMap() {
        try {
            int status = GooglePlayServicesUtil
                    .isGooglePlayServicesAvailable(mActivity);
            if (status == ConnectionResult.SUCCESS) {
                Log.d("sreedhu", "Google Play Service Available");
                gmo = (new GoogleMapOptions()).zoomControlsEnabled(true)
                        .rotateGesturesEnabled(true);
                mapFragment = SupportMapFragment.newInstance(gmo);
                map=mapFragment.getMap();   
                manager=getFragmentManager();
                FragmentTransaction fragmentTransaction = manager
                .beginTransaction();
                fragmentTransaction.add(R.id.mapFragmentHole, mapFragment);
                fragmentTransaction.commit();           
                manager.executePendingTransactions();
                            mapFragment=getMap();
            } else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
                ErrorDialogFragment.newInstance(status).show(
                        getFragmentManager(), "errorDialog");
            } else {
                Toast.makeText(mActivity, "Google Map v2 not available",
                        Toast.LENGTH_LONG).show();
                mActivity.popFragments();
            }

        } catch (Exception e) {
            Log.d("sreedhu", "play" + e.toString());
        }



    }

回答1:


executePendingTransactions seems not work like you expect it.

When MapFragment is created from code, you won't get GoogleMap from it until its onCreateView is called.

You need to call map=mapFragment.getMap(); and all code after it in onStart or onResume.




回答2:


Finally, I got the fix for this problem...

I include this below piece of snippet on onCreateView which solved my problem,

SupportMapFragment mFragment;
     mFragment = new SupportMapFragment() {
                @Override
                public void onActivityCreated(Bundle savedInstanceState) {
                    super.onActivityCreated(savedInstanceState);
                    if ((map = mFragment.getMap()) != null) {
                        setUpMap();
                    }
                }
            };

Once the map is prepared the SuppotMapFragment's onActivityCreated will get called there you can setup your map.



来源:https://stackoverflow.com/questions/15967000/google-map-v2-android-method-getmap-returns-null

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