[go: up one dir, main page]

Open In App

How to Use Firebase Firestore as a Realtime Database in Android?

Last Updated : 03 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Firebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realtime Database. Note that we are going to implement this project using the Java language. 

What we are going to build in this article? 

We will be building a simple application in which we will be showing a simple TextView. Inside that TextView, we will be updating the data from Firebase Firestore on a real-time basis. 

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. 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. 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">

    <TextView
        android:id="@+id/idTVHead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="5dp"
        android:layout_marginTop="30dp"
        android:text="Firebase Firestore as Realtime Database"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/purple_500"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/idTVUpdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHead"
        android:layout_marginTop="50dp"
        android:text="Updated Text"
        android:textAlignment="center"
        android:textColor="@color/purple_500"
        android:textSize="30sp" />
    
</RelativeLayout>

Step 5: 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.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;

public class MainActivity extends AppCompatActivity {

    // creating a variable for text view.
    TextView updatedTV;
    
    // initializing the variable for firebase firestore
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // initializing our text view.
        updatedTV = findViewById(R.id.idTVUpdate);
        
        // creating a variable for document reference.
        DocumentReference documentReference = db.collection("MyData").document("Data");
        
        // adding snapshot listener to our document reference.
        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                // inside the on event method.
                if (error != null) {
                    // this method is called when error is not null 
                    // and we get any error
                    // in this case we are displaying an error message.
                    Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (value != null && value.exists()) {
                    // if the value from firestore is not null then we are getting
                    // our data and setting that data to our text view.
                    updatedTV.setText(value.getData().get("updateValue").toString());
                }
            }
        });
    }
}

Step 6: Adding data to the Firebase Firestore console

Go to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner.   

After clicking on this screen you will get to see the below screen with your all project inside that select your project.  

Inside that screen click n Firebase Firestore Database in the left window.  


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 just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MyData. After that provide the Document ID as Data and inside the Field write down updateValue, and inside the Value provide your Text you want to display. And click on the Save button.

You will get to see the data added inside the Firebase Console.  

After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the updateValue field and you can get to see Realtime update on your device. 

Output:

In the below video we are updating the data when the app is running and it is showing the Realtime Updates in our app. 



Previous Article
Next Article

Similar Reads

Realtime Database vs Firestore
Realtime Database:Firebase is a real-time database that is a JSON datastore.It's totally unstructured which is a blessing and a curse.It is the Firebase’s first and original cloud-based database.This real-time database demonstrates very low latency.Firebase Database Rules is the only security option for realtime database. What makes real-time datab
3 min read
How to Create a Dynamic Video Player in Android with Firebase Realtime Database?
Most of the apps use the video player to display so many videos inside their application. So for playing the video the app plays the video from its video URL. But what if we want to update that video on a real-time basis. So, in that case, we have to update our database and then later on we have to update our APK. So this is not an efficient way to
8 min read
How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.
7 min read
How to Upload Excel Sheet Data to Firebase Realtime Database in Android?
Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous for its Firebase Realtime Database. By using Firebase Realtime Database in
6 min read
How to Delete Data from Firebase Realtime Database in Android?
In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase. What we are going to build in this article? We will be showing a simple AlertBox when the user long clicks on the item of RecyclerView. It will have two options. (Delete a
4 min read
User Authentication and CRUD Operation with Firebase Realtime Database in Android
Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for the backend database and handling the database. In this article, we will take a look at the implementation of the Firebase Realtime Database in Android. In this
15+ min read
Android Jetpack Compose - Retrieve Data From the Firebase Realtime Database
Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is its Firebase Realtime Database. By using Firebase Realtime Database in your ap
8 min read
Android Jetpack Compose - Add Data to Firebase Realtime Database
Firebase Realtime Database provides us with a feature to give Real-time updates to your data inside your app within milliseconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at How to add data to Firebase Realtime Database in Android using Jetpack Compose. A sample video is given
10 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading a website into your app which can be changed dynam
8 min read
Android Jetpack Compose - Retrieve Data From Firebase Realtime Database in ListView
Firebase Realtime Database provides us with a feature to give Real-time updates to your data inside your app within milliseconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for our ListView in Android using Jetpack Compose.
8 min read
How to Retrieve Data from Firebase Realtime Database in Android ListView?
Firebase Realtime Database provides us a feature to give Real-time updates to your data inside your app within milli-seconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for our ListView in Android. In this ListView, we will
7 min read
How to Retrieve PDF File From Firebase Realtime Database in Android?
When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, databa
8 min read
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Realtime Database?
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 V
7 min read
How to Retrieve Data from the Firebase Realtime Database in Android?
Firebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realtime Database. By using Firebase Realtime Database
7 min read
How to Save Data to the Firebase Realtime Database in Android?
Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Fire
9 min read
How to Download Firebase Realtime Database Data in Excel File?
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. We require No programming on the firebase side which makes it easy to use its features more efficiently. It provides services to android, iOS, web, and many more. It provides c
2 min read
Flutter - Realtime Database in Firebase
Firebase helps developers to build and run their apps successfully, its backend developed by Google. Firebase is very easy to use for beginners, it provides many functionalities like Firebase Authentication, Cloud Firestore, Realtime Database, Firebase Storage, etc which help to build and optimize the application. In this article, we will learn abo
5 min read
Setting Up and Configuring Firebase Realtime Database
Firebase Realtime Database is a cloud-hosted NoSQL database that allows us to store and sync data between our users in real-time. It is a powerful tool for building applications that require live updates, such as chat apps, collaborative tools, and real-time analytics. In this article, we will learn about the Firebase Realtime Database, the process
6 min read
Data Organization in Firebase Realtime Database
Firebase Realtime Database is a powerful tool that allows us to store and synchronize data in real-time across all clients. However, organizing data effectively in Firebase Realtime Database can be challenging for beginners. Proper data organization is important for efficient data retrieval, minimizing data transfer costs, and ensuring scalability.
7 min read
Firebase Realtime Database: Reading and Writing Data
Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients. In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, write data or read data to Firebase Realtime Database
7 min read
Firebase Realtime Database
Firebase Realtime Database is a powerful NoSQL cloud database that enables real-time data storage and synchronization across all clients. It's particularly suited for applications requiring live updates, such as chat apps and collaborative tools. By following the setup instructions and using the provided examples we can take the help of Firebase Re
7 min read
How to push data into firebase Realtime Database using ReactJS ?
Firebase is a popular backend-as-a-service platform that provides various services for building web and mobile applications. One of its key features is the Realtime Database, which allows developers to store and sync data in real-time. In this article, we will explore how to push data into the Firebase Realtime Database using ReactJS. The following
2 min read
How to Retrieve Image from Firebase in Realtime in Android?
When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into our app. But what if we want to change that image a
4 min read
Android Jetpack Compose - Retrieve Image From Firebase in Realtime
When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into our app. But what if we want to change that image a
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 we are going to build in this article? We will be cr
9 min read
How to Update Data in Firebase Firestore in Android?
In the previous article, we have seen on How to Add Data to Firebase Firestore in Android, How to Read the data from Firebase Firestore in Android. Now we will see How to Update this added data inside our Firebase Firestore. Now we will move towards the implementation of this updating data in Android Firebase. What we are going to build in this art
10 min read
Android Jetpack Compose - Update Data in Firebase Firestore
In the previous article, we have seen How to Add Data to Firebase Firestore in Android, How to read the data from Firebase Firestore in Android. Now we will see How to Update this added data inside our Firebase Firestore. Now we will move towards the implementation of this updating data in Android Firebase using Jetpack Compose. We will be creating
13 min read
Android Jetpack Compose - Delete Data in Firebase Firestore
In the previous article, we have taken a look at How to add, read and update data from our application in Firebase Firestore. In this article, we will take a look at How to implement a functionality in our application so that we will be able to delete data from Firebase Firestore in our android application using Jetpack Compose. A sample video is g
7 min read
How to Delete Data from Firebase Firestore in Android?
In the previous article, we have seen on How to Add Data, Read Data, and Update data in Firebase Firestore in Android. Now we will see How to Delete this added data inside our Firebase Firestore. So we will move towards the implementation of this deleting data in Android Firebase.   What we are going to build in this article?   We will be adding a
6 min read
Android Jetpack Compose - GridView using Firebase Firestore
GridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the
10 min read
Practice Tags :
three90RightbarBannerImg