Implement RecyclerView in android and show dynamic data?

How to create Recyclerview using List Adapter.

Implement  RecyclerView in android and show dynamic data?

In this article, we will cover :

  1. Why ListView is needed?
  2. How RecyclerView took over ListView?
  3. implementation of ReyclerView withListAapter. For better understanding, we will create a sample project 😉

Why ListView is needed?

As we know most of the apps these days uses scrollable screen, like WhatsApp chats, Facebook posts, YouTube videos. Have you seen something in common? The layout is the same, only the data that is changed!. Think practically, you cannot manually add all those views by yourself, because you don't know the number of contents at runtime. E.g: you don't know how many chats I will have.

ListView gif

For that reason, we require ListView that helps us to display horizontally/vertically scrollable collection of views.

How RecyclerView took over Listview

  • First of all RecyclerView was created to fullfill the drawback of ListView. Creating views is expensive when it comes to a long list, it indeed became costly. Suppose a food ordering application with a list of food, there could be 100 or thousands of food items, on your mobile screen you see only 10 (assume the size limit). So how did these views are drawn over screen?, let's find out.

    ListView simply create new views every time you scroll for new items, i.e. if 1000 items are on the list ListView will create 1000 views. Which is very costly to create and draw.

    In this situation, Recyclerview will create only once the number of it views needed to present on screen (10 in this case). But what if I scroll?. Don't worry dev, when you scroll down, the upper views are recycled to use as new bottom views, with changed data, that's all.

RecyclerView.png

  • In, RecyclerView things like animating over addition or removal of items are already implemented without you having to do anything.
  • ListView only supported Vertical Scrolling with Row displayed Views whereas RecyclerView supports Horizontal, Grid and staggered layouts, yo just have to mention the type using LayoutManager.

Project time gif

Let's Implement Recycler View with ListAdapter.

As of now, you have pretty much of idea why we use RecyclerView. RecyclerView makes it very easy to show large sets of data. All we just need to provide data and the layout (how it should look) and it dynamically creates the elements for you. Now let's create a project named RecyclerView_fun.

Ope Android Studio and follow these steps:-

  1. Create a project :

    • Click on New Project 1.png

    • Select Empty Activity., hit NEXT

2.png

  • Choose a app and package name, hit FINISH.

3.png

  1. Define RecyclerView in XML

    • open activity_main.xml

      Start typing <recyclerView. Auto suggest will appear, click that, or manually type or copy from below.

1.png

   <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
   />
  1. Create Single Item Layout, that would be shown as a list in RecyclerView.

    • Right click in res -> New -> Layout Resource File -> Select

      1.png

    • Give a name like item_student because we will show students' data.

    2.png

    • Create a design as well, as you like, I've created a simple one :p

    3.png

  2. Create a model class, the data source (type of object we are going to show)

    • Create a data class StudentModel with a name, roll number properties.

    1.png

    RecyclerView is ready, item_view ready and data Source Ready too. Now we need someone to bind them up. Here comes the Adapter. Adapter is a bridge between View and Data, it basically takes layout and data then binds both and show on RecyclerView.

Nowadays, we use ListAdapter over RecyclerView.Adapter() as it provides good features in regard to add/delete items.

ListAdapter is not equal to ListView.

  1. Create a ListAdapter

    • Create a class StudentAdapter that extends ListAdapter<>

    2.png

    • Listadapter takes 2 type parameter:

      • First: Type of the Lists this Adapter will receive.
      • Second: A class that extends ViewHolder that will be used by the adapter.

      It should look something like that.

    3.png

    • Implement member by hovering on class Name:

    4.png

    • Now construct method onCreateViewHolder, it is called when RecyclerView needs a new [ViewHolder] of the given type to represent an item. Create a view and return it.

    ViewHolder.png

    • Inside MyViewHolder I got access to item_student, take reference of individual views so that I can bind dynamic data to it.

    myViewHolder.png

    • Time to implement, onBindViewHolder which is called by RecyclerView to display the data at the specified position. This method should update the contents of [ViewHolder.itemView] to reflect the item at the given position.

    data feedint.png

    But still ListAapter giving us red signal, because it takes an object of DiffUtil.ItemCallback class as an argument. Which reduces the pain of explicitly calling ofnotifyDataSetChanged, notifyDataSetRemoved etc. methods. This callback will check old and new list in the most optimal way. So let's give it an Companion object

    diff.png

    • The first method areContentsTheSame() is used to check does two items have the same data or not
    • The other method areItemsTheSame() is used to check if two object has the same item or not.

    acllback.png

    As you can see, areContentsTheSame checks for roll number as it is unique. And the second one checks for object equivalence.

    ListAdapter Implementation Completed, all set lets Warp things up.

  2. Set up RecyclerView with Adapter:

    1. Take reference of RecyclerView

      val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
      
    2. Set up Layout manager

      recyclerView .layoutManager = LinearLayoutManager(this)
      
  3. Get the data (either from local or internet)

    Well, my data source is :

       private fun dummyData(): List<StudentModel> {
           val list : ArrayList<StudentModel> = ArrayList()
           for(i in 1..20){
               list.add(StudentModel("Android", i))
           }
           return list
       }
    
  4. Create an object of StudentAdapter and set it with recyclerView

       val adapter =  StudentAdapter()
       recyclerView.adapter = adapter
    
  5. Submit List of data to adapter, so that it can start working😉

      adapter.submitList(data)
    
  6. Final Result

[I removed the item background color, normally it looks better]

phone2.png

Get The full code From 😽Github