Предложения AutocompleteTextView всегда выбирают первый элемент в предложениях - PullRequest
0 голосов
/ 30 декабря 2018

Я столкнулся с проблемой, которую не могу решить.Я создал AutoCompleteTextView, который отображает отфильтрованные предложения из удаленных данных JSON.Окно предложений всплывает нормально и фильтруется правильно.У меня есть две проблемы, которые я не могу понять.

  1. При выборе элемента предложения текст в AutoCompleteTextView всегда устанавливается на первый элемент в исходном массиве предложений, независимо от того, отфильтрованы ли данные.
  2. При удалении символов в AutocompleteTextview, если оно становится пустым, генерируется исключение нулевого указателя

Код моего пользовательского адаптера:

package tz.co.fsm.fas;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class office_locations_adapter extends ArrayAdapter<office_location_data> implements Filterable {
    private Context context;
    private List<office_location_data> items, tempItems, suggestions;
    int row_layout;

    public office_locations_adapter(Context context, int row_layout, List<office_location_data> items) {
        super(context, row_layout, items);
        this.context = context;
        this.row_layout = row_layout;
        this.items = items;
        tempItems = new ArrayList<>(items); 
        suggestions = new ArrayList<>();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(row_layout, parent, false);
        }

        office_location_data office = items.get(position);

        if (office != null) {
            TextView lbloffice = view.findViewById(R.id.rowtxtOfficeLocation);
            if (lbloffice != null) {
                lbloffice.setText(office.getOffice_location());
            }
        }

        return view;
    }

    // This is important as it returns the count of the new arraylist when we filter it.
    @Override
    public int getCount() {
        return items.size();
    }

    // Method to return the filter
    @Override
    public Filter getFilter() {
        return performFiletring;
    }

    // Create a new filter. Here we perform the filtering results and use this in the getFilter() method
    Filter performFiletring = new Filter() {
        @Override
        public CharSequence convertResultToString(Object resultValue) {
            String str = ((office_location_data) resultValue).getOffice_location();
            return str;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            // We have some text to search
            if (constraint != null) {
                // CLear the suggestions array
                suggestions.clear();
                // Find the rows which match and add them to suggestions
                for (office_location_data offices : tempItems) {
                    if (offices.getOffice_location().toLowerCase().contains(constraint.toString().toLowerCase())) {
                        suggestions.add(offices);
                    }
                }
                // Pass the filter results to the next step publish results
                FilterResults filterResults = new FilterResults();
                filterResults.values = suggestions;
                filterResults.count = suggestions.size();
//                System.out.println(filterResults.count);
                return filterResults;
            } else {
                return new FilterResults();
            }
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            items = (List) results.values;
            if (results.count > 0) {
                //suggestions = (office_location_data) results.values;
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };
}

1 Ответ

0 голосов
/ 30 декабря 2018

Нашел проблему.Метод publishResults() был неправильным:

@Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<office_location_data> items = (ArrayList<office_location_data>) results.values;
            if (results != null && results.count > 0) {
                clear();
                for (office_location_data offices : suggestions) {
                    add(offices);
                    notifyDataSetChanged();
                }
            } else {
                notifyDataSetInvalidated();
            }
        }

Вот как я это сделал.

...