2016-04-29 5 views
0

Я пытаюсь использовать 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; 
} 
+0

Если customer.getName() равно нулю, то вы бы NullPointerException одну строку ниже его , Вы не указали, что получаете в publishResults(), я предполагаю, что вы получаете «пустой фильтр»? Кроме того, я предполагаю, что вы расширяете ArrayAdapter, чего не следует делать, если вы планируете использовать настраиваемую фильтрацию, поскольку этот адаптер предназначен для стандартных сценариев. – Luksprog

+0

где взяты ваши данные? – pskink

+0

@pskink Я извлекаю данные из «Realmdb» и отлично набирает. Вот почему я могу получить счет –

ответ

0

ясно метод getView функция() может быть причиной проблемы. Поэтому, пожалуйста, проверьте его код, для какого списка массивов вы очищаете.

Еще одна проблемы в том, что вы используете State customer = items.get(position); в getView() и используя suggestions.add(customer); в performFiltering(CharSequence constraint)

Надеются, что это помогает.

0

Итак, я сам исправил проблему. Таким образом, я использую нормальный BaseAdapter и расширить Filterable Таким образом, для тех, которые, возможно, потребуется, как использовать RealmDB с AutoCompleteTextView там вы идете

public class LgasAutoCompleteAdapter extends BaseAdapter implements Filterable { 

private static final String TAG = "LgasAutoComp"; 
private Context mContext; 
private List<Lga> mResult = new ArrayList<>(); 
private LayoutInflater inflater; 

public LgasAutoCompleteAdapter(Context mContext) { 
    this.mContext = mContext; 
} 

@Override 
public int getCount() { 
    return mResult.size(); 
} 

@Override 
public Object getItem(int position) { 
    return mResult.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

@Override 
public View getView(int position, View view, ViewGroup parent) { 
    if (inflater == null) 
     inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    if (view == null) 
     view = inflater.inflate(R.layout.item_baker_autocomplete, parent, false); 

    Lga lga = mResult.get(position); 

    TextView customerNameLabel = (TextView) view.findViewById(R.id.bakerName); 
    TextView bakerAddress = (TextView) view.findViewById(R.id.bakerAddress); 

    if (lga != null) { 
     if (customerNameLabel != null) { 
//    Log.i(MY_DEBUG_TAG, "getView Customer Name:"+customer.getName()); 
      customerNameLabel.setText(lga.getName()); 
      bakerAddress.setVisibility(View.GONE); 
     } 
    } 

    return view; 
} 

@Override 
public Filter getFilter() { 
    return new Filter() { 
     @Override 
     protected FilterResults performFiltering(CharSequence charSequence) { 
      return null; 
     } 

     @Override 
     protected void publishResults(CharSequence constraint, FilterResults filterResults) { 
      if (constraint != null) { 
       //String query = constraint.toString().toLowerCase(); 
       mResult = filterStates(constraint.toString()); 
       Log.e(TAG, ""+mResult.size()); 
       notifyDataSetChanged(); 
      } else { 
       notifyDataSetInvalidated(); 
      } 
     } 
    }; 
} 

@NonNull 
private List<Lga> filterStates(String query) { 
    Realm mRealm = RealmUtils.getRealmInstance(mContext); 
    return mRealm.where(Lga.class) 
      .contains("name", query) 
      .or() 
      .beginsWith("name", query) 
      .findAll(); 
} 
}