首页 > 解决方案 > 我已经在地图 fagment 上集成了 AutocompleteSupportFragment。当我点击地点搜索时。应用程序崩溃了

问题描述

我已经在地图 fagment 上集成了 AutocompleteSupportFragment。当我点击地点搜索时。应用程序崩溃了。它给出了error.java.lang.NullPointerException:必须设置地点字段。

 AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
          getChildFragmentManager().findFragmentById(R.id.autocomplete_frag);

        if (autocompleteFragment != null) {
            autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
        }

        if (autocompleteFragment != null) {
            autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
                @Override
                public void onPlaceSelected(@NonNull Place place) {
                    // TODO: Get info about the selected place.
       Toast.makeText(getContext(),place.getName(),Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onError(@NonNull Status status) {
                    // TODO: Handle the error.
                    Toast.makeText(getContext(),"Error",Toast.LENGTH_SHORT).show();

                }
            });
        }

标签: google-places-apigoogleplacesautocomplete

解决方案


我有同样的问题,谷歌开发者文档没有告诉你初始化 Places 所需的步骤(为什么他们会包括那个......),但你需要做的就是在初始化autoCompleteFragment变量的地方添加以下代码片段.

    if (!Places.isInitialized()) {
        Places.initialize(getApplicationContext(), "YOUR_API_KEY);
    }

干杯


推荐阅读