0

I have 10 items in my activity. They are displayed in a RecyclerView. The itms are stored in a list;

List<CustomItem> items = new ArrayList<>();

I pass them to the RecyclerView adapter like so:

recyclerView.setAdapter(new RVAdapter(this, items));

Now, whenever I do filter the items by a string query, so that the recycler view displays a subset of the items by description, for instance, I have to pass a filtered list of items to the recycler view, like so:

List<CustomItem> filteredItems = CustomItem.filterByQuery(items, query);

and then I:

adapter.setItemList(filteredItems);
notifyDataSetChanged();

-> which sets the filtered items in place of the items I sent to it in the constructor, and effectively overrids the activity items because they both point to the same objects in memory.

And I realized that by filtering in order to display a subset of results, I am overriding the acitivy's list of items, because it is shared by the activity and the RecyclerView

However, of all the code samples and tutorials I've seen on RecyclerView, I've never seen anyone do a deep copy of the list of items and pass it to the RV, so what am I missing here?

Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180
  • where does your data come from? is it sqlite database or some net api respose? – pskink Jun 12 '16 at 09:47
  • I get it from the server, then store it in the DB and pass it to the Activity so that it can store it in memory and work with it – Kaloyan Roussev Jun 12 '16 at 09:51
  • then use [this](https://gist.github.com/Shywim/127f207e7248fe48400b) adapter, as you can see it is `Filterable` so you can just call `getFilter().filter()` on it – pskink Jun 12 '16 at 10:06
  • of course like in "normal" `CursorAdapter` you need either to override `runQueryOnBackgroundThread` or call `setFilterQueryProvider` – pskink Jun 12 '16 at 12:23

1 Answers1

1

I found the answer in the comments below the accepted answer here: How to filter a RecyclerView with a SearchView

To quote:

@LalitThapa Just look at the constructor of my ExampleAdapter above. The second line should be interesting for you because that's where I make a copy of the List passed into the Adapter. What you want to have is two separate Lists. One in your Activity or Fragment which contains all items and a second List in your Adapter which contains only the filtered icons. Your problem is that you use the same List instance for both. – Xaver Kapeller Jan 17 at 19:05

Community
  • 1
  • 1
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180