Reputation: 141
hi i am developing one app where i have implemented recycler view and searchview in fregement.i get the filter product first time according to text change. But when i delete text one by one all list will be empty.Notheing can display at the end .
Here is my code from my fragement
Upvotes: 3
Views: 937
Reputation: 19427
As i see the main problem is you're manipulating the List
your adapter is populated from, but you do not have a "copy" of the original dataset.
Something like this should work:
ArrayList<ProductList> plistarray; // these are instance variables
ArrayList<ProductList> plistarrayCopy; // in your adapter
// ...
public void filter(String text) {
if (plistarrayCopy == null) {
plistarrayCopy = new ArrayList<>(plistarray);
}
if (text.isEmpty()) {
plistarray.clear();
plistarray.addAll(plistarrayCopy);
plistarrayCopy = null;
} else {
text = text.toLowerCase();
ArrayList<Device> filteredList = new ArrayList<>();
for (ProductList pList : plistarrayCopy) {
if (pList.getPtitle().toLowerCase().contains(text)) {
filteredList.add(pList);
}
}
plistarray.clear();
plistarray.addAll(filteredList);
}
notifyDataSetChanged();
}
Upvotes: 1
Reputation: 3711
You are continuously operating on single array
named plistarray
here in filter()
method you have cleared plistarray
and again used the same to find the records. so you should use some other array for you adapter rather than plistarray
public void filter(String text) {
if (text.isEmpty()) {
plistarray.clear();
plistarray.addAll(plistarray);
} else {
ArrayList<ProductList> result = new ArrayList<>();
text = text.toLowerCase();
//after clearing the array again you are using same array to find the items from
for (ProductList item : plistarray) {
if (item.getPtitle().toLowerCase().contains(text)) {
result.add(item);
}
}
//you have cleared all the contains here
plistarray.clear();
// and added only result related items here
plistarray.addAll(result);
}
notifyDataSetChanged();
}
Upvotes: 2
Reputation: 3843
I think the problem is in the if (text.isEmpty()) {
block of filter
method.
Here you clear the plistarray
list and add that empty list in plistarray.addAll(plistarray);
Instead of this add your original datalist for the plistarray.addAll(); This will resolve your empty list problem.
Remember this, when you perform the search always first make a dummy/copy of original list in constructor of adapter, and use this dummy to restore the data.
Hope, this will solve your problem.
Upvotes: 1