How to Read Data from Firebase Firestore in Android?

17 Jan, 2021
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. 
We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. 
Step 1: Working with the activity_main.xml file
Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. 
XML
<!--Button for showing the list of added courses--><Button  android:id="@+id/idBtnViewCourses"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:layout_margin="10dp"  android:text="View Added Courses"  android:textAllCaps="false" />
Now below is the updated code for the activity_main.xml file after adding the above code snippet.
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">      <!--Edittext for getting course Name-->    <EditText        android:id="@+id/idEdtCourseName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="10dp"        android:layout_marginTop="20dp"        android:layout_marginEnd="10dp"        android:hint="Course Name"        android:importantForAutofill="no"        android:inputType="text" />      <!--Edittext for getting course Duration-->    <EditText        android:id="@+id/idEdtCourseDuration"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="10dp"        android:layout_marginTop="20dp"        android:layout_marginEnd="10dp"        android:hint="Course Duration in min"        android:importantForAutofill="no"        android:inputType="time" />      <!--Edittext for getting course Description-->    <EditText        android:id="@+id/idEdtCourseDescription"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="10dp"        android:layout_marginTop="20dp"        android:layout_marginEnd="10dp"        android:hint="Course Description"        android:importantForAutofill="no"        android:inputType="text" />      <!--Button for adding your course to Firebase-->    <Button        android:id="@+id/idBtnSubmitCourse"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:text="Submit Course Details"        android:textAllCaps="false" />      <!--Button for showing the list of added courses-->    <Button        android:id="@+id/idBtnViewCourses"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:text="View Added Courses"        android:textAllCaps="false" />  </LinearLayout>
Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView
To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. 
Step 3: Now we will move towards the implementation of XML in our Course Details activity
Navigate to the app > res > layout > activity_course_details.xml and add the below code to it. 
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"    tools:context=".CourseDetails">      <!--Recycler view for displaying        our data from Firestore-->    <androidx.recyclerview.widget.RecyclerView        android:id="@+id/idRVCourses"        android:layout_width="match_parent"        android:layout_height="match_parent" />      <!--Progress bar for showing loading screen-->    <ProgressBar        android:id="@+id/idProgressBar"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true" />      </RelativeLayout>
Step 4: Now we will create a card layout for our item of RecyclerView
To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add 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:id="@+id/idCVCOurseItem"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_margin="5dp"    app:cardCornerRadius="6dp"    app:cardElevation="4dp">      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="2dp"        android:orientation="vertical"        android:padding="4dp">          <!--Textview for displaying our Course Name-->        <TextView            android:id="@+id/idTVCourseName"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:padding="2dp"            android:text="CourseName"            android:textColor="@color/purple_500"            android:textSize="18sp"            android:textStyle="bold" />                  <!--Textview for displaying our Course Duration-->        <TextView            android:id="@+id/idTVCourseDuration"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:padding="2dp"            android:text="Duration"            android:textColor="@color/black" />                  <!--Textview for displaying our Course Description-->        <TextView            android:id="@+id/idTVCourseDescription"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:padding="2dp"            android:text="Description"            android:textColor="@color/black" />              </LinearLayout>  </androidx.cardview.widget.CardView>
Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items
For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. 
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;  import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;  import java.util.ArrayList;  public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {    // creating variables for our ArrayList and context    private ArrayList<Courses> coursesArrayList;    private Context context;      // creating constructor for our adapter class    public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) {        this.coursesArrayList = coursesArrayList;        this.context = context;    }      @NonNull    @Override    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        // passing our layout file for displaying our card item        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));    }      @Override    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {        // setting data to our text views from our modal class.        Courses courses = coursesArrayList.get(position);        holder.courseNameTV.setText(courses.getCourseName());        holder.courseDurationTV.setText(courses.getCourseDuration());        holder.courseDescTV.setText(courses.getCourseDescription());    }      @Override    public int getItemCount() {        // returning the size of our array list.        return coursesArrayList.size();    }      class ViewHolder extends RecyclerView.ViewHolder {        // creating variables for our text views.        private final TextView courseNameTV;        private final TextView courseDurationTV;        private final TextView courseDescTV;          public ViewHolder(@NonNull View itemView) {            super(itemView);            // initializing our text views.            courseNameTV = itemView.findViewById(R.id.idTVCourseName);            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);        }    }}
Step 6: Working with the CourseDetails.java file
After creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. 
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;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 CourseDetails extends AppCompatActivity {      // creating variables for our recycler view,     // array list, adapter, firebase firestore    // and our progress bar.    private RecyclerView courseRV;    private ArrayList<Courses> coursesArrayList;    private CourseRVAdapter courseRVAdapter;    private FirebaseFirestore db;    ProgressBar loadingPB;          @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_course_details);                  // initializing our variables.        courseRV = findViewById(R.id.idRVCourses);        loadingPB = findViewById(R.id.idProgressBar);                  // initializing our variable for firebase        // firestore and getting its instance.        db = FirebaseFirestore.getInstance();                  // creating our new array list        coursesArrayList = new ArrayList<>();        courseRV.setHasFixedSize(true);        courseRV.setLayoutManager(new LinearLayoutManager(this));                  // adding our array list to our recycler view adapter class.        courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);                  // setting adapter to our recycler view.        courseRV.setAdapter(courseRVAdapter);                  // below line is use to get the data from Firebase Firestore.        // previously we were saving data on a reference of Courses        // now we will be getting the data from the same reference.        db.collection("Courses").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.                            loadingPB.setVisibility(View.GONE);                            List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();                            for (DocumentSnapshot d : list) {                                // after getting this list we are passing                                 // that list to our object class.                                Courses c = d.toObject(Courses.class);                                                                  // and we will pass this object class                                // inside our arraylist which we have                                 // created for recycler view.                                coursesArrayList.add(c);                            }                            // after adding the data to recycler view.                            // we are calling recycler view notifuDataSetChanged                            // method to notify that data has been changed in recycler view.                            courseRVAdapter.notifyDataSetChanged();                        } else {                            // if the snapshot is empty we are displaying a toast message.                            Toast.makeText(CourseDetails.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(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();            }        });    }}
Step 7: Working with the MainActivity.java file
In the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so.
Java
// adding onclick listener to view data in new activityviewCoursesBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // opening a new activity on button click                Intent i = new Intent(MainActivity.this,CourseDetails.class);                startActivity(i);            }   });
Below is the updated code for the MainActivity.java file.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;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.CollectionReference;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.FirebaseFirestore;  public class MainActivity extends AppCompatActivity {      // creating variables for our edit text    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;      // creating variable for button    private Button submitCourseBtn, viewCoursesBtn;      // creating a strings for storing    // our values from edittext fields.    private String courseName, courseDuration, courseDescription;      // creating a variable    // for firebasefirestore.    private FirebaseFirestore db;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // getting our instance        // from Firebase Firestore.        db = FirebaseFirestore.getInstance();          // initializing our edittext and buttons        courseNameEdt = findViewById(R.id.idEdtCourseName);        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);        submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);        viewCoursesBtn = findViewById(R.id.idBtnViewCourses);          // adding onclick listener to view data in new activity        viewCoursesBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // opening a new activity on button click                Intent i = new Intent(MainActivity.this,CourseDetails.class);                startActivity(i);            }        });          // adding on click listener for button        submitCourseBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                  // getting data from edittext fields.                courseName = courseNameEdt.getText().toString();                courseDescription = courseDescriptionEdt.getText().toString();                courseDuration = courseDurationEdt.getText().toString();                  // validating the text fields if empty or not.                if (TextUtils.isEmpty(courseName)) {                    courseNameEdt.setError("Please enter Course Name");                } else if (TextUtils.isEmpty(courseDescription)) {                    courseDescriptionEdt.setError("Please enter Course Description");                } else if (TextUtils.isEmpty(courseDuration)) {                    courseDurationEdt.setError("Please enter Course Duration");                } else {                    // calling method to add data to Firebase Firestore.                    addDataToFirestore(courseName, courseDescription, courseDuration);                }            }        });    }      private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) {          // creating a collection reference        // for our Firebase Firetore database.        CollectionReference dbCourses = db.collection("Courses");          // adding our data to our courses object class.        Courses courses = new Courses(courseName, courseDescription, courseDuration);          // below method is use to add data to Firebase Firestore.        dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {            @Override            public void onSuccess(DocumentReference documentReference) {                // after the data addition is successful                // we are displaying a success toast message.                Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show();            }        }).addOnFailureListener(new OnFailureListener() {            @Override            public void onFailure(@NonNull Exception e) {                // this method is called when the data addition process is failed.                // displaying a toast message when data addition is failed.                Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show();            }        });    }}
After completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. 
After completing this Run your app and see the output of the code.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java