【发布时间】:2020-04-22 18:14:07
【问题描述】:
此方法是否在单例模式下运行?还是每次都为用户创建新会话?
在edittext更改监听器上调用以下方法。
@NonNull
private ArrayList<PlaceAutocomplete> getPredictions(@NonNull CharSequence constraint) {
final ArrayList<PlaceAutocomplete> resultList = new ArrayList<>();
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
//https://gist.github.com/graydon/11198540
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setLocationBias(bounds)
.setCountry("PK")
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
Task<FindAutocompletePredictionsResponse> autocompletePredictions = placesClient.findAutocompletePredictions(request);
// This method should have been called off the main UI thread. Block and wait for at most
// 60s for a result from the API.
try {
Tasks.await(autocompletePredictions, 60, TimeUnit.SECONDS);
} catch (@NonNull ExecutionException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
if (autocompletePredictions.isSuccessful()) {
FindAutocompletePredictionsResponse findAutocompletePredictionsResponse = autocompletePredictions.getResult();
if (findAutocompletePredictionsResponse != null)
for (AutocompletePrediction prediction : findAutocompletePredictionsResponse.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getPrimaryText(STYLE_NORMAL).toString(), prediction.getFullText(STYLE_BOLD).toString()));
}
return resultList;
} else {
return resultList;
}
}
该方法会在 editText 中的每个文本更改时调用。
【问题讨论】:
标签: java android google-maps google-places-api googleplacesautocomplete