11

I am trying to make an app that will be loading news from the network and will be updating dynamically. I am using a RecyclerView and CardView to display the content. I use Jsoup to parse sites. I don't think that my code is needed because my question is more theoretical than practical. I want to understand the process of dynamic updating using notifyDataSetChanged(). In my main activity I get all the headers and add them to list. But I need to wait untill all the items are loaded to start displaying them. I would really appreciate if someone could post a sample code of what I'm trying to do because I couldn't find a lot of information about combining ViewHolder, Adapter and RecyclerView.

Kiran Benny Joseph
  • 6,755
  • 4
  • 38
  • 57
Vendetta8247
  • 592
  • 1
  • 5
  • 30

1 Answers1

25

In your RecyclerView adapter, you should have a ArrayList and also one method addItemsToList(items) to add list items to the ArrayList. Then you can add list items by call adapter.addItemsToList(items) dynamically. After all your list items added to the ArrayList then you can call adapter.notifyDataSetChanged() to display your list.

Hope this is clear!

Xcihnegn
  • 11,579
  • 10
  • 33
  • 33
  • this part is clear, thank you. But how does it correspond with a ViewHolder? – Vendetta8247 Feb 16 '15 at 13:38
  • `ViewHolder describes an item view and metadata about its place within the RecyclerView`. Your dynamical updating list no different with normal `ViewHolder` – Xcihnegn Feb 16 '15 at 14:04
  • 3
    I have figured out how to finish it. The only thing that you didn't mention is that the `adapter.notifyDataSetChanged()` must be called in the UI thread. And to do that I used `runOnUiThread(new Runnable(){...})` – Vendetta8247 Feb 16 '15 at 16:07
  • without your codes hard to know what process you are using to get your list items, seems you are using a thread to do that, but better you should use background thread `Asynctask` to get list items, then you can communicate with main UI in `onPostExecute(listItems)` – Xcihnegn Feb 16 '15 at 17:20
  • my code was a bit wrong as I had wrong parameters in `postExecute()`. But still using it in a separate thread inside AsyncTask is what I was looking for because it adds each item separately without waiting for all the list to load! And I think it might help me in future when I will have much more headers! – Vendetta8247 Feb 16 '15 at 23:37
  • Yes `Asynctask` is much easier to use for downloading list items (http://developer.android.com/reference/android/os/AsyncTask.html) – Xcihnegn Feb 17 '15 at 08:19