Я пытаюсь использовать AutoCompleteTextView
для фильтрации, и у меня проблема с фильтром. Он возвращает все элементы в ArrayList
вместо фильтрованных. Ниже мой код:AutoCompleteTextView Text Filtering
Filter nameFilter = new Filter() {
@Override
public String convertResultToString(Object resultValue) {
String str = ((State)(resultValue)).getName();
Log.e("Conv"+TAG, str);
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
suggestions.clear();
for (State customer : itemsAll) {
Log.e("Ite "+TAG, "" + itemsAll.size());
Log.e("Cons " + TAG, constraint.toString());
Log.e("Sta" + TAG, customer.getName()); //This is always null
if(customer.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestions.add(customer);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<State> filteredList = (ArrayList<State>) results.values;
if(results != null && results.count > 0) {
clear();
Log.e("D "+TAG, ""+results.count);
for (State c : filteredList) {
Log.e("The "+TAG, c.getName() + " " + c.getId());
add(c);
notifyDataSetChanged();
}
} else {
Log.e(TAG, "Empty Filter");
notifyDataSetChanged();
}
}
};
А потом я начал вход вокруг, и я заметил, эта линия всегда нулевая Log.e("Sta" + TAG, customer.getName()); //This is always null
в то время как эта линия Log.e("Cons " + TAG, constraint.toString());
и эта линия Log.e("Ite "+TAG, "" + itemsAll.size());
никогда не нуль. Ограничение не может быть нулевым, если только текст не передан. Но для первого объекта будет null, если itemsAll.size()
не является нулевым или пустым. Я запутался. И ниже, мой List
инициализации
private static final String TAG = "StateAdapter";
private ArrayList<State> items;
private ArrayList<State> itemsAll;
private ArrayList<State> suggestions;
private Context context;
private int viewResourceId;
public StateAutoCompleteAdapter(Context context, int resource, int textViewResourceId, ArrayList<State> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
this.items = objects;
this.itemsAll = new ArrayList<State>(items);
this.suggestions = new ArrayList<State>();
this.viewResourceId = resource;
}
И для
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
State customer = items.get(position);
if (customer != null) {
TextView customerNameLabel = (TextView) v.findViewById(R.id.bakerName);
TextView bakerAddress = (TextView) v.findViewById(R.id.bakerAddress);
if (customerNameLabel != null) {
// Log.i(MY_DEBUG_TAG, "getView Customer Name:"+customer.getName());
customerNameLabel.setText(customer.getName());
bakerAddress.setVisibility(View.GONE);
}
}
return v;
}
Если customer.getName() равно нулю, то вы бы NullPointerException одну строку ниже его , Вы не указали, что получаете в publishResults(), я предполагаю, что вы получаете «пустой фильтр»? Кроме того, я предполагаю, что вы расширяете ArrayAdapter, чего не следует делать, если вы планируете использовать настраиваемую фильтрацию, поскольку этот адаптер предназначен для стандартных сценариев. – Luksprog
где взяты ваши данные? – pskink
@pskink Я извлекаю данные из «Realmdb» и отлично набирает. Вот почему я могу получить счет –