Question -
The main problem is when I run the app I don't see a filterable search working it always shows an invalid search even if I search the exact related text results. The app doesn't crash as I have already handled the null pointer exception.
I got a filterable search which is used on appBar. I have used the recycler view inside Fragment - "Home"
Home Fragment Code
private RecyclerView recyclerVFragHomeSc;
adapterRecVHomeFrag adapter;
Toolbar toolbar;
private MenuItem menuItem;
private SearchView searchView;
private ArrayList<dataModelRecVFragHome> dataHolder;
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.custom_toolbar_menu,menu);
menuItem = menu.findItem(R.id.search_button);
searchView = (SearchView)menuItem.getActionView();
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//mysearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(adapter != null){
adapter.getFilter().filter(newText);
}else{
Toast.makeText(getContext(), "invalid search", Toast.LENGTH_SHORT).show();
}
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
ADAPTER CLASS
ArrayList<dataModelRecVFragHome> dataHolderBackup;
public adapterRecVHomeFrag(ArrayList<dataModelRecVFragHome> dataHolder) {
this.dataHolder = dataHolder;
dataHolderBackup = new ArrayList<>(dataHolder);
}
@Override
public Filter getFilter() {
return filter;
}
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence keyword) {
//tempo array list for filtered data
ArrayList<dataModelRecVFragHome> filteredData = new ArrayList<>();
if(keyword.toString().isEmpty())
filteredData.addAll(dataHolderBackup);
else {
for (dataModelRecVFragHome obj : dataHolderBackup) {
if (obj.getTitle().toString().toLowerCase().trim().contains(keyword
.toString().toLowerCase().trim()) ||
obj.getDescription().toString().toLowerCase().trim().contains(keyword
.toString().toLowerCase().trim()))
filteredData.add(obj);
}
}
FilterResults results = new FilterResults();
results.values = filteredData;
return results;
}
//Main thread ui
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
dataHolder.clear();
dataHolder.addAll((ArrayList<dataModelRecVFragHome>)filterResults.values);
notifyDataSetChanged();
}
};