gpt4 book ai didi

android - Google Places API AutocompleteSupportFragment 空指针异常

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:40 24 4
gpt4 key购买 nike

我正在使用 Google Places API 获取自动完成支持 fragment 以获取包含位置建议的搜索栏。我按照这里给出的教程 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);
}
});

空指针异常出现在这一行

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

也就是说 setPlaceFields 不能在空引用上调用。

最佳答案

首先,您必须初始化 Places(引用 here):

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

如果你想在Activity中使用AutocompleteSupportFragment,你可以这样获取:

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

如果你想在Fragment中使用AutocompleteSupportFragment,你可以这样获取:

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

关于android - Google Places API AutocompleteSupportFragment 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com