HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is mostly seen in many E-commerce apps to indicate categories in the app. As we have already seen in Amazon Shopping App. So in this article, we will take a look at creating a Dynamic Horizontal Recycler View in Android using Firebase Firestore. But in this article, we will be using Firebase Realtime Database 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 Recycler View in which we will be showing different languages used in Computer Science such as C++. 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
Refer to Adding Firebase to Android App. You can read About Firebase Realtime Database from here.
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.
<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
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout 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 = "#000" android:textSize = "15sp" /> < androidx.recyclerview.widget.RecyclerView android:id = "@+id/idRVItems" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginTop = "5dp" android:background = "#fff" /> </ LinearLayout > |
Step 5: 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 content.xml and add the below code to it.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout 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 = "#fff" android:backgroundTint = "#fff" 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 = "#fff" /> </ LinearLayout > |
Step 6: 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 and give a name to your class. Here we have given the name as CardModel and add the below code to it.
Java
public class CardModel { // variables for storing // our image and name. private String name; private String imgUrl; public CardModel() { // empty constructor // required for firebase. } // constructor for our object class. public CardModel(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 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 AdapterCard and add the 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 AdapterCard extends RecyclerView.Adapter<AdapterCard.ViewHolder> { private ArrayList<CardModel> dataModalArrayList; private Context context; // constructor class for our Adapter public AdapterCard(ArrayList<CardModel> dataModalArrayList, Context context) { this .dataModalArrayList = dataModalArrayList; this .context = context; } @NonNull @Override public AdapterCard.ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { // passing our layout file for displaying our card item return new AdapterCard.ViewHolder(LayoutInflater.from(context).inflate(R.layout.content, parent, false )); } @Override public void onBindViewHolder( @NonNull AdapterCard.ViewHolder holder, int position) { // setting data to our views in Recycler view items. final CardModel modal = dataModalArrayList.get(position); holder.courseNameTV.setText(modal.getName()); // we are using Picasso to load images // from URL inside our image view. Picasso.with(holder.courseIV.getContext()).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 androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView courseRV; private ArrayList<CardModel> dataModalArrayList; private AdapterCard dataRVAdapter; private DatabaseReference 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 = FirebaseDatabase.getInstance().getReference(); // 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 AdapterCard(dataModalArrayList, this ); // setting adapter to our recycler view. courseRV.setAdapter(dataRVAdapter); loadrecyclerViewData(); } private void loadrecyclerViewData() { DatabaseReference reference = FirebaseDatabase.getInstance().getReference( "topics" ); reference.addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { dataModalArrayList.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { CardModel modelCourses1 = dataSnapshot1.getValue(CardModel. class ); dataModalArrayList.add(modelCourses1); dataRVAdapter = new AdapterCard(dataModalArrayList, MainActivity. this ); courseRV.setAdapter(dataRVAdapter); } } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } } |
Here We are going to show how to add Data to Firebase
Go to the firebase console > open your project and click on the Realtime Database in the left panel.
Step 1: Firstly We will create a node of name topics
Step 2: Then we will add our item node in the database with name and image link
Step 3: Here we can see that we have added all the item
Now run the app and see the output of the code below.