Home   Courses   Blog   About

How to display data with RecyclerView for Android Beginners

What is RecyclerView

I must say that this is a very fancy name for a very common component. When I was searching for an answer how to explain what RecyclerView is, a colleague of mine just said: “This is a data component you use now!” plain and simple. This is a component that displays data in different ways and is made with contemporary techniques to make scrolling as smooth as possible and to make development easier. With RecyclerView you can display a table of data, display items in a grid or if you want you can also do a Staggered layout like Pinterest does it with every item being a different size.
We will show, what you need for a RecyclerView, with a small app that will show a list of cities. This way you will see what you need for RecyclerView and how to start an app with a lists. The bonus feature will be the images we will show for each city, since images are from the web and this is not that easy to implement without our little trick.

Create a new project

To start learning you must start a new project first so that you will be able to use all the knowledge. Take a look at our blog on How to create a new project

Adding Support Library for RecyclerView

We must start with the hardest part. RecyclerView and a few other elements are a part of external library. We must add this external library called Support Library. Support Library is a library for components and other very helpful classes, provided by Google, that enables us to work with modern components, and components that were added later in Android Development. Here you will find RecyclerView, ViewPager, GridLayout, Material Design components ...

  • So how can we use Support Library?

    • For older Android Studio version (before 3.1)
      We need to add a line of code to build.gradle (bold line bellow). Be aware, that in your project there will be more lines of code already there, you need to insert it into group dependencies.



      This line of code will instruct Android Studio to go and download all the libraries we need to start working with our project. After the download, Android Studio will also build these libraries for us and sync the project.

    • Android Studio 3.1
      In a newer version of Android Studio you can just click the download icon beside RecyclerView in Palette and Android Studio will add it automatically for us.

 

Design of the screen

The design of the screen is simple. We will just add a RecyclerView to main activity. You need to open activity_main.xml in your res/layout folder.

  1. Remove Hello World TextView
  2. Add the RecyclerView
    • Name it “cities”
    • Connect constraints to all the borders (left, right, top, bottom) and set margin to 0dp (item already has margin).

Layout for our item (Design for a city)

We will show a list of cities in our example, that is why we need to add a layout that will have all the components for the item (city).

  1. Let’s design our item. Add a new layout, right click on res/layout folder in your project
    • Add a new layout
    • Name it item_city
    • (just in case, if you right click on res (not layout) folder, you will get the choice New/Android Resource file (on picture below), for that choice you would need to change Resource type to Layout as well).
  2. We will add two TextViews and one ImageView to ConstraintLayout in the layout
    • Add ImageView
      • Name it “image”
      • Set scaleType to fitStart
      • Connect constraints to left/upper/bottom border. Left and bottom constraint should have margin 8dp so that it looks nicer.
    • Add first TextView
      • Name it “name”
      • Change text to “(name)”
      • Connect constraints to ImageView and to top and right border. Set the margin for left constraint to 8dp
    • Add second TextView
      • Name it “description”
      • Change text to “(description)”
      • Connect constraints to ImageView and top constraint to “name” TextView. Right constraint should be connected to the border. Set the margin for left and bottom constraint to 8dp.
    • After you link all the constraints the screen should look something like this

 

We need a data class to show a list (Class City)

I know that the goal is to display data in the RecyclerView, but we need something to show first. We decided that a list of cities is a great way to showcase data. We have added a few cities for you to start with as well, but you can add more of them if you want.

We need a class to hold data for us. This will be a class named City.

  1. Add a new Class and name it City.
    • Right click on your package, eg. java/com.codebrainer.recyclerview
      Package selected
    • Select New/Java Class:
      Add a new class
    • Enter name (and then click OK)
      City class
  2. Next add these variables to our class (at the beginning of the class)



    Once we have added variables, we can use the Generate tool to add more code. We will use context menu for that (right click on code). We will use Generate for Constructor and for Getters And Setters.
  3. First we will generate a constructor for the class

    The great thing about Generate tool is that we can choose which properties we want to use and we also have control over the way the code will look. For now just go ahead and select all the properties.

    This is the code that will be created for you.



  4. Next we will generate Getters And Setters, this step is good practice on how to build a new class quickly.

    Select all the properties once again.
  5. This is how the code for class Cities should look like



  6. We will now prepare another function, that will populate data with a few cities. We will call it initCities. We will insert this function in our MainActivity.java, put it below onCreate method.



    What the code does is that it uses the constructor we have added before (new City(...)) and makes ArrayList of cities for us. We will then use this list with our adapter. Adapter is the next step.



Let’s add an RecyclerView.Adapter

Adapter is a class that will take care of preparing views for items and change data for each element RecyclerView needs to display. In other words this a link between RecyclerView and our data.

  1. To start you need to add a new class named CityAdapter (right click your package like you did before for Class City and choose New/Class)
    • Name it CityAdapter
    • This class will extend RecyclerView.Adapter (just choose it from dropdown in Super class)
      Select super class RecyclerView
    • When you entered all the data click OK to create class.

      We will end up with code that will look like this

      Now we need to update it.

  2. First we can implement all the required methods (select all of them).

    Now the code will look like this.
  3. Let’s add a variable for the list of cities. Put this code at the below the class CityAdapter declaration.



  4. Since we already have a list of cities we can replace the code for counting number of items. We do this with size method on cities array. Now it should look like this.



  5. Now that we have a base for our adapter and the layout for the item, we can implement a ViewHandler class for our adapter. This is a class that will init view for each item in RecyclerView. This class will hold references to all the components of the item and also to our data item. This will be a class within a class and it will be a “public static class”. We will name it ViewHolder
    • What does public static class mean? This is just a way of creating a new class, that is inside another class so that you can use it linked to a parent class (it is in the same name space). In our case we will use class with CityAdapter.ViewHolder. It just looks nicer.



    • The code consists mostly of variables that will enable us to set values for the components.
    • In the constructor of the ViewHolder we will find all the elements within the view and link them to the variables with method FindViewById.
  6.  Next will be the initialization of viewHolder. Initialization happens in the onCreateViewHolder method. It looks a little bit heavy on functions, but what it does is, it makes a view (or group of views) with a given layout.



    • LayoutInflater is a class, that takes care of making views out of xml layout design.
    • At the end we return a new ViewHolder. RecyclerView will then reference ViewHolder for us and take care of preparing next ones in order to have a smooth scroll.
  7.  The next task is to link the current item with the viewHolder in other words we need to show appropriate data for the item.



    • Notice, that we do not have an image jet. We will add it later.
  8.  If we want to use our fancy Adapter, we will need a constructor to init data within the adapter. Our constructor will have one parameter and it will be an ArrayList of cities.




Connecting all the dots and displaying data

We have prepared all the classes and we will use them in MainActivity.java. We have already added initCities method when we were working on the City data class. Now we will use the Adapter.

  1. We need to add a variable for recycler and for adapter (put them just after declaration of our MainAcitvity class



  2. The last piece of code is the one that will link it all together, and we will put all of it after the first two lines of the onCreate method (those lines were already prepared for us and they make layout activity_main come to life).



    • The first line is a local variable for our ArrayList of cities, this calls our intiCities method and populates the list.
    • Next lines are for recyclerView, first we just connect the variable with findViewById. Next we set the layout manager for recyclerView, we will use LinearLayoutManager, this will make a list (remember, you have Grid and Staggered as well).
    • The last lines link the adapter and the recyclerView, this lines are the final link to making data appear in the list.
  3.  And the result (if we run the app)

 

Adding images from the internet to RecyclerView

Our list just looks sad without images and we need to add them. For that we will use Picasso library made by Square. This library makes working with images easier. We will use its ability to load images from the web. All we need is a simple line of code, but let’s go step by stap

  1. Adding Picasso library. You need to add a line of code within the dependencies group of build.gradle (app)



    • You will need to sync the project after adding this line in order for Android Studio to build the library.
  2.  We need permission for the internet as well to show images with an url. You will add this permission in AndroidManifest.xml. Add this line before the application tag.



    • We need this permission in order to get the images from the web. And we will do this with imageURL value for the City object.
  3.  Connecting imageView and Picasso will happen in onBindViewHolder of CityAdapter. Put this line of code at the end of the method.



  4. This is it, let’s run the app and see what happens.

 

 

Where can we go from here

Now that we have shown how to use RecyclerView, we can now show data in our app, but if we want to take it a step further, there are a few more topics we can research for RecyclerView

  • Reaction when an item is pressed and reacting to user input, showing details about an item, redirecting to another screen according to the selection...
  • Custom divider having a nice divide will usually be a part of the design
  • Swipe to delete is a common function used to interact with an item in the list.
  • Animations of items when they appear or disappear
  • Paging and loading data from REST API

The solution