mapFragment.getMap() returns null

放肆的年华 提交于 2019-11-29 13:52:12
GLee

Try moving all code that references your GoogleMap to onStart() or onResume(). The map in a map fragment isn't instantiated until after the fragment has gone through onCreateView (link), which happens after the parent activity has gone through onCreate(). Also, you need to check your GoogleMap for null regardless, because if google play services aren't installed, or the map isn't available for some other reason, it will be null.

From what I read this could be because the fragment is not yet fully displayed and therefore no map exists?

Correct.

Any ideas how to fix it?

Actually use the layout file, by calling setContentView(), and get rid of all the FragmentTransaction stuff. You can then retrieve the already-created SupportMapFragment and use it:

setContentView(R.layout.activity_main);

SupportMapFragment mapFrag=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapFragment);

You have to implement OnMapReadyCallback, define its public void onMapReady(GoogleMap map) and use it to operate on the fragment as stated in the Google API

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