Oftentimes, Android developers require to display a long list of data items retrieved from backend onto the current activity. This can be acheived using RecyclerView.
Here’s the final outcome of this tutorial.
The above data has been fetched from the collection Recipes stored in the Cloud Firestore of Firebase as shown below:
To implement a basic RecyclerView three sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice.
1. The Card Layout: the card layout is an XML layout which will be treated as an item for the list created by the RecyclerView.
2. The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained through database.
3. The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView.
Let’s see how to acheive this. For this we first need to add RecyclerView to our activity_main.xml. Implementing it within ScrollView is a good practise as there is expected to be a lot of data when fetching from firebase to be inflated in a RecyclerView.
After this, create a sample data class for all the properties and behavior of your class. Here, we name it as Recipe.java.
(Note: The name of the variables and methods in this class must be kept in alignment with the fields mentioned in the document of the required collection.)
Once we are done, we need an Adapter class for holding and inflating the data of each document retrieved from Firestore collection.
Here, we are using FirestoreRecyclerAdapter.
To implement onClick functionality for RecyclerView items, a holder class needs to be created. Get position of item/adapter clicked.
Now that we have our collection class and an Adapter, this is how our MainActivity.java must look like.
base of type Query must have a query for fetching data from database. It could be something like
base = FirebaseFirestore.getInstance().collection("recipes");
And there you go!