这是我的适配器中的简单过滤器类:
public class Adapter extends ArrayAdapter<T>
{
private List<T> origItems;
private List<T> filteredData = null;
private ItemFilter mFilter = new ItemFilter();
public AdapterAppOrContact(Context context, List<T> items)
{
super(context, R.layout.row_adapter_app, items);
origItems = items;
filteredData = items;
}
@Override
public int getCount() {
return filteredData.size();
}
// ....
private class ItemFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint)
{
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<T> list = origItems;
int count = list.size();
final ArrayList<T> newList = new ArrayList<T>(count);
String filterableString ;
for (int i = 0; i < count; i++)
{
filterableString = list.get(i).getName();
if (filterableString.toLowerCase().contains(filterString))
{
newList.add(list.get(i));
}
}
results.values = newList;
results.count = newList.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
{
filteredData = (ArrayList<T>) results.values;
notifyDataSetChanged();
}
}
}
当您查看final ArrayList<T> newList = new ArrayList<T>(count);
这意味着,就我看来,此过滤器永远不会返回null
列表。但我看到以下情况:调用publishResults
后,我的filteredData
为空。
这怎么可能发生? filteredData
是私有的,并且在我的适配器的构造函数和过滤器的publishResults
回调中的任何其他位置都不会更改。
有什么想法吗?我可以用空检查解决它,但我很好奇是什么原因
编辑 - Stacktrace
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.app.package.adapters.AdapterAppOrContact.getCount(AdapterAppOrContact.java:40)
at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:828)
at android.widget.AbsListView$AdapterDataSetObserver.onChanged(AbsListView.java:6373)
at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
at android.widget.ArrayAdapter.notifyDataSetChanged(ArrayAdapter.java:310)
at com.app.package.adapters.AdapterAppOrContact$ItemFilter.publishResults(AdapterAppOrContact.java:129)
...