How to Create Dynamic ListView in Android using Firebase Firestore?
Last Updated :
14 Aug, 2024
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 implementation of ListView using Firebase Firestore in Android. Now, let's move towards the implementation of this project.
What we are going to build in this project?
We will be building a simple ListView application in which we will be displaying a list of courses along with images in our ListView. We will fetch all the data inside our ListView from Firebase Firestore. 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.
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.
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"?>
<RelativeLayout
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">
<ListView
android:id="@+id/idLVCourses"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
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: Create a layout file for our item of ListView
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_lv_item and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:padding="2dp"
app:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Image view for displaying our image-->
<ImageView
android:id="@+id/idIVimage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="8dp"
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_marginStart="10dp"
android:layout_marginTop="40dp"
android:layout_toEndOf="@id/idIVimage"
android:padding="3dp"
android:text="Category Text"
android:textAlignment="center"
android:textColor="@color/black" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Step 7: Now create an Adapter class for our ListView
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 CoursesLVAdapter 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.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class CoursesLVAdapter extends ArrayAdapter<DataModal> {
// constructor for our list view adapter.
public CoursesLVAdapter(@NonNull Context context, ArrayList<DataModal> dataModalArrayList) {
super(context, 0, dataModalArrayList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// below line is use to inflate the
// layout for our item of list view.
View listitemView = convertView;
if (listitemView == null) {
listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_lv_item, parent, false);
}
// after inflating an item of listview item
// we are getting data from array list inside
// our modal class.
DataModal dataModal = getItem(position);
// initializing our UI components of list view item.
TextView nameTV = listitemView.findViewById(R.id.idTVtext);
ImageView courseIV = listitemView.findViewById(R.id.idIVimage);
// after initializing our items we are
// setting data to our view.
// below line is use to set data to our text view.
nameTV.setText(dataModal.getName());
// in below line we are using Picasso to
// load image from URL in our Image VIew.
Picasso.get().load(dataModal.getImgUrl()).into(courseIV);
// below line is use to add item click listener
// for our item of list view.
listitemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on the item click on our list view.
// we are displaying a toast message.
Toast.makeText(getContext(), "Item clicked is : " + dataModal.getName(), Toast.LENGTH_SHORT).show();
}
});
return listitemView;
}
}
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.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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 {
// creating a variable for our list view,
// arraylist and firebase Firestore.
ListView coursesLV;
ArrayList<DataModal> dataModalArrayList;
FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// below line is use to initialize our variables
coursesLV = findViewById(R.id.idLVCourses);
dataModalArrayList = new ArrayList<>();
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// here we are calling a method
// to load data in our list view.
loadDatainListview();
}
private void loadDatainListview() {
// below line is use to get data from Firebase
// firestore using collection in android.
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);
// after getting data from Firebase we are
// storing that data in our array list
dataModalArrayList.add(dataModal);
}
// after that we are passing our array list to our adapter class.
CoursesLVAdapter adapter = new CoursesLVAdapter(MainActivity.this, dataModalArrayList);
// after passing this array list to our adapter
// class we are setting our adapter to our list view.
coursesLV.setAdapter(adapter);
} 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) {
// we are displaying a toast message
// when we get any error from Firebase.
Toast.makeText(MainActivity.this, "Fail to load data..", Toast.LENGTH_SHORT).show();
}
});
}
}
After adding the above code add the data to Firebase Firestore in Android.
Step 9: Adding the data to Firebase Firestore in Android
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.
After clicking on the Create Database option you will get to see the below screen.
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.
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:
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build applications across platformsâfrom web and mobile apps to enterprise software. It is known for its Write Once, Run Anywhere capability, meaning code written in Java can run on any device that supports the Java Virtual Machine (
11 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read