我正在尝试为我的适配器类(扩展BaseAdapter)添加一个过滤器。
启动应用程序后,每件事情都工作正常,但是当重新创建活动时(通过屏幕旋转或调用onCreate),应用程序停止工作并使力关闭错误
当我删除此行时,重新创建活动没有问题
MainActivity.this.adapter.getFilter().filter(cs);
但是调试器显示错误在
super.onCreate(savedInstanceState);
这是我的主要活动onCreate功能:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Updator().execute();//Updator is a AsyncTask to update adapter
EditText inputSearch = (EditText) findViewById(R.id.editText1);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count)
{
MainActivity.this.adapter.getFilter().filter(cs);//after screen rotation - application stops working when executing this line
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
这是我在自定义适配器类中的过滤器方法:
private class CustomListFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0)
{
results.values = original;
results.count = original.size();
}
else
{
final ArrayList<App> nlist = new ArrayList<App>();
int count = original.size();
App pkmn;
String value;
for (int i=0; i<count; i++)
{
pkmn = original.get(i);
value = pkmn.getName().toLowerCase();
if (value.contains(prefix))
{
nlist.add(pkmn);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
{
mApps = (ArrayList<App>)results.values;
if (mApps.size() > 0)
notifyDataSetChanged();
else
notifyDataSetInvalidated();
}
}
答案 0 :(得分:0)
我的猜测(没有看到logcat跟踪)就是你在问题行上得到一个空指针异常:
MainActivity.this.adapter.getFilter().filter(cs);
这可能是由于adapter
为空,或者getFilter()
的返回为空。
确保在重新创建Activity时创建非null变量!