RecyclerView for Android Beginners - How to display data - Main image

Intermediate

RecyclerView for Android Beginners - How to display data

RecyclerView 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.

Miha Cirman - CodeBrainer
Miha Cirman
15 min read

What is RecyclerView

I must say that this is a very fancy name, even though it is a very common component. When I was searching for an answer on 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 not only as smooth as possible but also 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 as 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. Furthermore, in this way, you will see what you need for RecyclerView and how to start an app with a list. 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, so take a look at our blog on How to create a new project.

 

Adding Support Library for RecyclerView

Like it or not, we must start with the hardest part. RecyclerView and a few other elements are a part of an external library so 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 below). But be aware that in your project, there will already be more lines of code there, so make sure to insert it into group dependencies.

Java
Group dependencies code - Java - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

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 or later
    However, in a newer version of Android Studio, you can click the download icon beside RecyclerView in Palette, and Android Studio will add it automatically for us.

Android Studio 3.1. palette

 

Design of the screen in RecyclerView

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

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

Programming is a skill best acquired by practice and example rather than from books. Have a look at our Android Development course and get the skills you need.

Start Now

 

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
    New layout file
    • Name it item_city
      RecyclerView display data

    • (just in case, if you right click on res (not layout) folder, you will get the choice New/Android Resource file (on the picture below), for that choice you would need to change Resource type to Layout as well).display data

  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
      Recyclerview-screen

 

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, so we 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, e.g. java/com.codebrainer.recyclerview
      add a class name it city
    • Select New/Java Class:
      RecyclerView new java class
    • Enter a name (and then click OK).
      RecyclerView display data

  1. Next, add these variables to our class (at the beginning of the class).
    Java
    Adding variables to a class code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

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

  • First, we will generate a constructor for the class.
    Generate Constructor

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, but for now, go ahead and select all the properties.

RecyclerView display data

This is the code that will be created for you.

Java
RecyclerView variable code - Java - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!

  • As for the next step, we will generate Getters And Setters since this step is good practice on how to build a new class quickly.
    generate Getters And Setters
  • Select all the properties once again.
    RecyclerView display data
  • This is how the code for class Cities should look like.
    Java
    Cities class code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



  • We will now prepare another function, that will populate data with a few cities, and we will call it initCities. Afterwards, we will insert this function in our MainActivity.java, put it below the onCreate method.
    Java
    Function to populate data - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

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. The adapter is the next step.

Programming is a skill best acquired by practice and example rather than from books. Have a look at our Android Development course and get the skills you need.

Start Now

Let's add a RecyclerView.Adapter

An adapter is a class that will take care not only of preparing views for items but will also 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 the RecyclerView.Adapter (choose it from a dropdown in Super class).
      RecyclerView adapter
    • When you entered all the data click OK to create the class.
      Create the class
    • We will end up with code that will look like this.
      RecyclerView adapter code
    • Now we need to update it.

  2. First, we can implement all the required methods (select all of them).
    Implement methods
    • Now the code will look like this.
      RecyclerView adapter code

  3. Let's add a variable for the list of cities. Put this code at the below the class CityAdapter declaration.
    Java
    Extra variable code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



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

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

Implement a ViewHandler class

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. Basically, 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 namespace). In our case, we will use the class with CityAdapter.ViewHolder. Obviously, since it just looks nicer.
    Java
    ViewHandler class code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



  • 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.
  • Next will be the initialisation of viewHolder. Initialisation 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.
    Java
    ViewHolder initialisation code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

 

XML layout design

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

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



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

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

 

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.

  • We need to add a variable for recycler and for the adapter, so put them just after the declaration of our MainAcitvity class.
    Java
    Variables for Recycler and adapter - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!

  • 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).
    Java
    Last piece of the code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



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

 

Adding images from the internet to RecyclerView

Our list just looks sad without images and we need to add them, so we will use Picasso library made by Square. This library makes working with images easier, therefore, 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 step.

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

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



  • Furthermore, you will need to sync the project after adding this line in order for Android Studio to build the library.
  • We need permission for the internet as well to show images with an url, so you will add this permission in AndroidManifest.xml. Add this line before the application tag.
    XML
    Internet permission - XML - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



  • 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.
  • Connecting imageView and Picasso will happen in onBindViewHolder of CityAdapter so put this line of code at the end of the method.
    Java
    Connecting imageView and Picasso code - Java - CodeBrainer

    Thanks for reading!

    If you like our code, you can give back by sharing this article!



  • This is it, so let's run the app and see what happens.
    RecyclerView final screen

 

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



Java
Complete recyclerView code - MainActivity - Java - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!



Java
Complete recyclerView code - CityAdapter - Java - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!



Java
Complete recyclerView code - City - Java - CodeBrainer

Thanks for reading!

If you like our code, you can give back by sharing this article!


Loading FB comments...