0

I have a ViewPager with 2 tabs. Each tab just holds a Fragment with a RecyclerView. The RecyclerView in the first tab holds a list of all Articles while the RecyclerView in the second tab only holds the list of user's favorite Articles. Each Article in the first tab has a button in the RecyclerView row that allows the user to favorite it. I want new favorites to be displayed automatically (without forcing the user to manually press the refresh button) when the user navigates to the second tab. How can I go about doing this? Essentially I need to add / remove items from the RecyclerView which contains the favorites, but from the first fragment.

Things I have tried

  • Call adapter.notifyDataSetChanged() in the onRefresh() method of the favorites fragment. This works, but the performance hit is big because notifyDataSetChanged() is not a cheap operation. I would like to avoid this if possible.
  • Tried following this guide, and implemented some interfaces. The problem is, when I try to reference the adapter in my fragment from the containing activity, the adapter is always null. I can post code if needed to show what I was doing if this is supposed to be possible.

Now I am considering using SQLite DB to store changes (favorite removals/additions) in the onClickListeners, and then checking that table in the onResume() method and processing the changes individually, one by one with notifyItemChanged()

Is there a better way to do this?

sparkitny
  • 1,503
  • 4
  • 18
  • 23
Ryan
  • 658
  • 8
  • 22
  • Where you getting your data from? `SQlite` or `internet` ? – Abu Yousuf Jan 28 '18 at 07:19
  • Both kind of. I store identifiers of the favorites `SQLite`. Then I use an API to pull down the individual favorites from the internet based on the keys stored in `SQLite` – Ryan Jan 28 '18 at 07:25

1 Answers1

0

For SQlite use CursorLoader to load data from SQlite. You can register to be notified when a data changed in a table. Then your loader will automatically load data again. Check this answer. Also check this Thread.

For getting data from internet you can use

  1. Communicate with 2 fragments via parent Activity. Check this and this answer. This tutorial is good for better understanding.
  2. LocalBroadcastManager to notify from one fragment to another fragment.
Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50