This is the searchview in MainActivity
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
return false;
}
@Override
public boolean onQueryTextChange(String text) {
servantAdapter.getFilter().filter(text);
//Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
return true;
}
});
}
And This is the Adapter
public class ServantAdapter extends RecyclerView.Adapter<ServantAdapter.ViewHolder>implements Filterable {
private List<Servant> mServant;
@Override
public Filter getFilter() {//The front omitted...
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
mServant = (List<Servant>) filterResults.values;
ServantAdapter.this.notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Servant> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = mServant;
} else {
filteredResults = getFilteredResults(constraint.toString().toLowerCase());
}
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected List<Servant> getFilteredResults(String constraint) {
List<Servant> results = new ArrayList<>();
for (Servant item : mServant) {
if (item.getName().toLowerCase().contains(constraint)) {
results.add(item);
}
}
return results;
}
Why when I run this program and imput something in the searchview the program is shut dowm and ReportErrors java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.Filter com.example.a76959.tired.ServantAdapter.getFilter()' on a null object reference
But if I use the Toast in the code ,the program can run regular and toast the message what I input(I didnt take the searchview in Toolbar or ActionBar,I only put it on the top of recyclerview in MainActivity.xml,I don't know if it has any effect ) Who can help me...(Thanks for read my poor English Orz..)