Nee*_*lye 3 android google-places-api google-places-autocomplete
我正在使用Google Places API来获取自动完成支持片段,以获取带有位置建议的搜索栏。我跟着这里给出的教程 商家信息自动填充
这是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" />
Run Code Online (Sandbox Code Playgroud)
这是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);
}
});
Run Code Online (Sandbox Code Playgroud)
空指针异常出现在这一行
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
Run Code Online (Sandbox Code Playgroud)
它说setPlaceFields不能在空引用上调用。
首先,您必须初始化Places(在此处参考):
// Add an import statement for the client library.
import com.google.android.libraries.places.api.Places;
// Initialize Places.
Places.initialize(getApplicationContext(), apiKey);
Run Code Online (Sandbox Code Playgroud)
如果要在活动中使用AutocompleteSupportFragment,则可以通过以下方式获取它:
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);
Run Code Online (Sandbox Code Playgroud)
如果要在片段内使用AutocompleteSupportFragment,则可以通过以下方式获取它:
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getChildFragmentManager().findFragmentById(R.id.autoCompleteFragment);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1103 次 |
| 最近记录: |