Google Places API AutocompleteSupportFragment空指针异常 [英] Google Places API AutocompleteSupportFragment Null pointer Exception

查看:240
本文介绍了Google Places API AutocompleteSupportFragment空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Places API来获取自动完成支持片段,以获取带有位置建议的搜索栏.我按照这里给出的教程 地方信息自动完成

I am using the Google Places API to get an autocomplete support fragment to get a search bar with location suggestions. I followed the tutorial given here Places Autocomplete

这是XML代码

<fragment
            android:id="@+id/autoCompleteFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />

这是Java代码

// Initialize the AutocompleteSupportFragment.
    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);

    // Specify the types of place data to return.
    autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

        // Set up a PlaceSelectionListener to handle the response.
    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
        }
        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });

空指针异常出现在此行上

The null pointer exception comes on this line

autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

其中说setPlaceFields不能在空引用上调用.

Which says that setPlaceFields cannot be called on a null reference.

推荐答案

首先,您必须初始化Places(参考

First of all, you have to initialize Places (reference here):

// Add an import statement for the client library.
import com.google.android.libraries.places.api.Places;
// Initialize Places.
Places.initialize(getApplicationContext(), apiKey);

如果要在活动中使用AutocompleteSupportFragment,则可以通过以下方式获取它:

If you want to use the AutocompleteSupportFragment inside an Activity, you can get it in this way:

AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
    getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);

如果要在Fragment中使用AutocompleteSupportFragment,则可以通过以下方式获取它:

If you want to use the AutocompleteSupportFragment inside a Fragment, you can get it in this way:

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

这篇关于Google Places API AutocompleteSupportFragment空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆