Место автозаполнения не работает должным образом - PullRequest
0 голосов
/ 21 января 2020

Я использую автозаполнение нового SDK в моем проекте.

реализация 'com.google. android .libraries.places: мест: 2.1.0'

Автозаполнение текстового обзора Я использую его для отображения данных. Проблема в том, что он работает правильно в первый раз, а не во второй. Список отображается не во второй раз и адрес кого-то. Иногда я получаю сообщение об ошибке: PlaceAutoCompleteAdapter: Место не найдено: 9010. Пожалуйста, помогите решить эту проблему.

public class PlaceAutocompleteAdapterNew extends ArrayAdapter<AutocompletePrediction> implements Filterable {
        PlacesClient placesClient;
        AutocompleteSessionToken token;
        private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
        private List<AutocompletePrediction> mResultList;
        private List<AutocompletePrediction> tempResult;
        Context context;
        private String TAG = "PlaceAutoCompleteAdapter";

        public PlaceAutocompleteAdapterNew(Context context, PlacesClient placesClient, AutocompleteSessionToken token) {
            super(context, android.R.layout.simple_expandable_list_item_1, android.R.id.text1);
            this.context = context;
            this.placesClient = placesClient;
            this.token = token;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View row = super.getView(position, convertView, parent);

            AutocompletePrediction item = getItem(position);

            TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
            textView1.setText(item.getPrimaryText(STYLE_BOLD));
            return row;
        }

        @Override
        public int getCount() {
            if (mResultList == null)
                return 0;
            else
                return mResultList.size();
        }

        @Override
        public AutocompletePrediction getItem(int position) {
            return mResultList.get(position);
        }

        @Override
        public Filter getFilter() {
            return new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults results = new FilterResults();
                    // Skip the autocomplete query if no constraints are given.
                    if (constraint != null) {
                        // Query the autocomplete API for the (constraint) search string.
                        mResultList = getAutoComplete(constraint);
                        if (mResultList != null) {
                            // The API successfully returned results.
                            results.values = mResultList;
                            results.count = mResultList.size();
                        }
                    }
                    return results;

                }

                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results != null && results.count > 0) {
                        // The API returned at least one result, update the data.
                        notifyDataSetChanged();
                    } else {
                        // The API did not return any results, invalidate the data set.
                        notifyDataSetInvalidated();
                    }
                }

                @Override
                public CharSequence convertResultToString(Object resultValue) {
                    // Override this method to display a readable result in the AutocompleteTextView
                    // when clicked.
                    if (resultValue instanceof AutocompletePrediction) {
                        return ((AutocompletePrediction) resultValue).getFullText(null);
                    } else {
                        return super.convertResultToString(resultValue);
                    }
                }
            };
        }

        private List<AutocompletePrediction> getAutoComplete(CharSequence constraint) {
            // 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();
            // Create a RectangularBounds object.

            // Use the builder to create a FindAutocompletePredictionsRequest.
            FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
                    .setTypeFilter(TypeFilter.ADDRESS)
                    .setSessionToken(token)
                    .setQuery(constraint.toString())
                    .build();

            placesClient.findAutocompletePredictions(request).addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
                @Override
                public void onSuccess(FindAutocompletePredictionsResponse response) {
                    for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
                        Log.e(TAG, prediction.getPrimaryText(null).toString());
                    }
                    tempResult = response.getAutocompletePredictions();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    if (exception instanceof ApiException) {
                        ApiException apiException = (ApiException) exception;
                        Log.e(TAG, "Place not found: " + apiException.getStatusCode());
                    }
                }
            });
            return tempResult;
        }
    }

1 Ответ

1 голос
/ 22 января 2020

Код ошибки указывает на проблему с местами API-биллинга, код 9010 означает, что вы превысили пределы запроса, разрешенные вашим биллингом. Автозаполнение мест не является бесплатным, но Google позволяет вам попробовать его несколько раз без установленного платежного аккаунта, прежде чем отклонять запросы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...