Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?
Next article icon

How to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is seen in many E-commerce apps to indicate categories in the app. And this RecyclerView is also dynamic so that the admin can add or remove any item from that RecyclerView at any time. So in this article, we will take a look at creating a dynamic Horizontal Recycler View in Android using Firebase. We will be using Firebase Firestore to display the items of RecyclerView. 

What we are going to build in this article? 

We will be building a simple application in which we will be displaying a horizontal RecyclerView in which we will be showing different technologies used in Computer Science. So we will represent this amazing computer technology in our Horizontal RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 



Step-by-Step Implementation

Step 1: Create a new Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.  

Step 2: Connect your app to Firebase 

After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.

firestore4-copy


Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.  

firestore5-copy


After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.

implementation ‘com.google.firebase:firebase-firestore:22.0.1’

After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.  

Step 3: Working with the AndroidManifest.xml file

For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.  

XML
<!--Permissions for internet--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context=".MainActivity">      <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:padding="10dp"         android:text="Dynamic Horizontal Recycler View"         android:textAlignment="center"         android:textColor="@color/purple_500"         android:textSize="15sp" />      <androidx.recyclerview.widget.RecyclerView         android:id="@+id/idRVItems"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="40dp"         android:background="@color/purple_500" />      </LinearLayout> 

Step 5: Now we will create a new Java class for storing our data  

For reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app's package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it.  

Java
public class DataModal {      // variables for storing our image and name.     private String name;     private String imgUrl;      public DataModal() {         // empty constructor required for firebase.     }      // constructor for our object class.     public DataModal(String name, String imgUrl) {         this.name = name;         this.imgUrl = imgUrl;     }      // getter and setter methods     public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public String getImgUrl() {         return imgUrl;     }      public void setImgUrl(String imgUrl) {         this.imgUrl = imgUrl;     } } 

Step 6: Now we will create a layout file for our item of RecyclerView 

Navigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_rv_item and add the below code to it.  

XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_gravity="center"     android:gravity="center"     android:orientation="vertical">      <!--Image view for displaying our image-->     <ImageView         android:id="@+id/idIVimage"         android:layout_width="100dp"         android:layout_height="100dp"         android:layout_margin="4dp"         android:background="@color/white"         android:backgroundTint="@color/white"         android:padding="3dp" />      <!--Text view for displaying our text -->     <TextView         android:id="@+id/idTVtext"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_margin="2dp"         android:padding="3dp"         android:text="Category Text"         android:textAlignment="center"         android:textColor="@color/white" />  </LinearLayout> 

Step 7: Now we will move towards creating an Adapter class

For creating a new Adapter class navigate to the app > java > your app's package name > Right-click on it and Click on New > Java class and name your java class as DataRVAdapter and add below code to it. Comments are added inside the code to understand the code in more detail.

Java
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast;  import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView;  import com.squareup.picasso.Picasso;  import java.util.ArrayList;  public class DataRVAdapter extends RecyclerView.Adapter<DataRVAdapter.ViewHolder> {     private ArrayList<DataModal> dataModalArrayList;     private Context context;      // constructor class for our Adapter     public DataRVAdapter(ArrayList<DataModal> dataModalArrayList, Context context) {         this.dataModalArrayList = dataModalArrayList;         this.context = context;     }      @NonNull     @Override     public DataRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         // passing our layout file for displaying our card item         return new DataRVAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.image_rv_item, parent, false));     }      @Override     public void onBindViewHolder(@NonNull DataRVAdapter.ViewHolder holder, int position) {         // setting data to our views in Recycler view items.         DataModal modal = dataModalArrayList.get(position);         holder.courseNameTV.setText(modal.getName());                  // we are using Picasso to load images         // from URL inside our image view.         Picasso.get().load(modal.getImgUrl()).into(holder.courseIV);         holder.itemView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 // setting on click listener                 // for our items of recycler items.                 Toast.makeText(context, "Clicked item is " + modal.getName(), Toast.LENGTH_SHORT).show();             }         });     }      @Override     public int getItemCount() {         // returning the size of array list.         return dataModalArrayList.size();     }      public class ViewHolder extends RecyclerView.ViewHolder {         // creating variables for our          // views of recycler items.         private TextView courseNameTV;         private ImageView courseIV;          public ViewHolder(@NonNull View itemView) {             super(itemView);             // initializing the views of recycler views.             courseNameTV = itemView.findViewById(R.id.idTVtext);             courseIV = itemView.findViewById(R.id.idIVimage);         }     } } 

Step 8: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java
import android.os.Bundle; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.List;  public class MainActivity extends AppCompatActivity {      private RecyclerView courseRV;     private ArrayList<DataModal> dataModalArrayList;     private DataRVAdapter dataRVAdapter;     private FirebaseFirestore db;      @Override     protected void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // initializing our variables.         courseRV = findViewById(R.id.idRVItems);          // initializing our variable for firebase         // firestore and getting its instance.         db = FirebaseFirestore.getInstance();          // creating our new array list         dataModalArrayList = new ArrayList<>();         courseRV.setHasFixedSize(true);          // adding horizontal layout manager for our recycler         // view.         courseRV.setLayoutManager(new LinearLayoutManager(             this, LinearLayoutManager.HORIZONTAL, false));          // adding our array list to our recycler view         // adapter class.         dataRVAdapter             = new DataRVAdapter(dataModalArrayList, this);          // setting adapter to our recycler view.         courseRV.setAdapter(dataRVAdapter);          loadrecyclerViewData();     }      private void loadrecyclerViewData()     {          db.collection("Data")             .get()             .addOnSuccessListener(new OnSuccessListener<                                   QuerySnapshot>() {                 @Override                 public void onSuccess(                     QuerySnapshot queryDocumentSnapshots)                 {                     // after getting the data we are calling                     // on success method and inside this                     // method we are checking if the                     // received query snapshot is empty or                     // not.                     if (!queryDocumentSnapshots.isEmpty()) {                         // if the snapshot is not empty we                         // are hiding our progress bar and                         // adding our data in a list.                         List<DocumentSnapshot> list                             = queryDocumentSnapshots                                   .getDocuments();                         for (DocumentSnapshot d : list) {                             // after getting this list we                             // are passing that list to our                             // object class.                             DataModal dataModal                                 = d.toObject(                                     DataModal.class);                              // and we will pass this object                             // class inside our arraylist                             // which we have created for                             // recycler view.                             dataModalArrayList.add(                                 dataModal);                         }                         // after adding the data to recycler                         // view. we are calling recycler                         // view notifyDataSetChanged method                         // to notify that data has been                         // changed in recycler view.                         dataRVAdapter                             .notifyDataSetChanged();                     }                     else {                         // if the snapshot is empty we are                         // displaying a toast message.                         Toast                             .makeText(                                 MainActivity.this,                                 "No data found in Database",                                 Toast.LENGTH_SHORT)                             .show();                     }                 }             })             .addOnFailureListener(new OnFailureListener() {                 @Override                 public void onFailure(@NonNull Exception e)                 {                     // if we do not get any data or any                     // error we are displaying a toast                     // message that we do not get any data                     Toast                         .makeText(MainActivity.this,                                   "Fail to get the data.",                                   Toast.LENGTH_SHORT)                         .show();                 }             });     } } 

Step 9: Now add the data to your Firebase Console

Search for Firebase in your browser and go to that website and you will get to see the below screen. 

After clicking on Go to Console option. Click on your project which is shown below.

After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. 

firestore1-copy


After clicking on the Create Database option you will get to see the below screen.  

firestore2-copy


Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen.  

firestore3-copy


Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console. 

You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for "name" and one filed for "imgUrl" and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added. 

Similarly, add more images by clicking on the “Add document” button. 

After adding these images run your app and you will get to see the output on the below screen. 

Output: 


Next Article
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

    How to Create Dynamic ListView in Android using Firebase Firestore?
    ListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the
    9 min read
    How to Create Dynamic Intro Slider in Android using Firebase Firestore?
    We have seen creating a basic Intro Slider in Android which is used to inform our users regarding the features of our app and many more. In this article, we will take a look at the implementation of dynamic Intro Slider in our app with the help of Firebase. With the help of Firebase Firestore, we ca
    11 min read
    How to Create Dynamic Bottom Sheet Dialog in Android using Firebase Firestore?
    Bottom Sheet Dialog is one of the famous Material UI Component which is used to display data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android us
    7 min read
    How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio
    Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let's connect the Realtime Database with an Android applic
    7 min read
    How to Read Data from Firebase Firestore in Android?
    In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase.  What w
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences