(google translate)
Intro: I have searched for this solution, but did not find it. If there is a duplicate of this problem, please let me know. thanks.
Problem: I created a storage application with the Room database and RecycleView. Then I looked for ways to add Search to my data. Everything went smoothly, but there was one problem. If the search word is reduced, then the search is limited to visible data. (Look at the screenshot)
I hope you understand. Please help me. I have seen a lot of tutorials but nothing works.
thank you
My Code: Filter in my Adapter
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
List<Barang> filteredList = new ArrayList<>();
if (charString.isEmpty()) {
filteredList.addAll(namaBarang);
} else {
for (Barang row : namaBarang) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getNamaBarang().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
namaBarang = (ArrayList<Barang>) filterResults.values;
notifyDataSetChanged();
}
};
}
MainActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
adapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// t = newText.;
adapter.getFilter().filter(newText);
return false;
}
And I have this too in my Adapter:
void setBarangs(List<Barang> barangs){
namaBarang = barangs;
notifyDataSetChanged();
}
My problem has been solved with this:
Thanks