L.M.Orz L.M.Orz - 3 years ago 216
Android Question

Searchview.setOnQueryTextListener NullPointException

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..)

Answer Source

When you are using servantAdapter.getFilter().filter(text); make sure the variable servantAdapter has been instantiated properly and is not null.

Use:

if (servantAdapter != null){
    servantAdapter.getFilter().filter(text);
}

Or:

if (servantAdapter == null){
    servantAdapter = new servantAdapter(/*params*/);
}
servantAdapter.getFilter().filter(text);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download