Open In App

How to Retrieve Data from the Firebase Realtime Database in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

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 in your app you can give live data updates to your users without actually refreshing your app. So in this article, we will be creating a simple app in which we will be using Firebase Realtime Database and retrieve the data from Firebase Realtime database and will see the Realtime data changes in our app. 

What we are going to build in this article?

We will be building a simple Android application in which we will be displaying a simple Text View. Inside that TextView, we will be displaying data from Firebase. We will see how Real-time data changes happen in our app by actually changing data on the server-side. Note that we are going to implement this project using the Java language. 

Note: You may also refer to How to Save Data to the Firebase Realtime Database in Android?

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 Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. 

After completing this process you will get to see the below screen. 

Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section. 

implementation ‘com.google.firebase:firebase-database:19.6.0’

If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app. 

Step 3: 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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/idTVRetrieveData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Retrieve Data"
        android:textAlignment="center"
        android:textColor="@color/purple_500"
        android:textSize="18sp" />
 
</RelativeLayout>


 
Step 4: Add internet permission in your AndroidManifest.xml file

Add the permission for the internet in the AndroidManifest.xml file. 

XML




<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


 
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.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
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;
 
public class MainActivity extends AppCompatActivity {
 
    // creating a variable for
    // our Firebase Database.
    FirebaseDatabase firebaseDatabase;
     
    // creating a variable for our
    // Database Reference for Firebase.
    DatabaseReference databaseReference;
     
    // variable for Text view.
    private TextView retrieveTV;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // below line is used to get the instance
        // of our Firebase database.
        firebaseDatabase = FirebaseDatabase.getInstance();
         
        // below line is used to get
        // reference for our database.
        databaseReference = firebaseDatabase.getReference("Data");
         
        // initializing our object class variable.
        retrieveTV = findViewById(R.id.idTVRetrieveData);
         
        // calling method
        // for getting data.
        getdata();
    }
 
    private void getdata() {
 
        // calling add value event listener method
        // for getting the values from database.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                // this method is call to get the realtime
                // updates in the data.
                // this method is called when the data is
                // changed in our Firebase console.
                // below line is for getting the data from
                // snapshot of our database.
                String value = snapshot.getValue(String.class);
                 
                // after getting the value we are setting
                // our value to our text view in below line.
                retrieveTV.setText(value);
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // calling on cancelled method when we receive
                // any error or we are not able to get the data.
                Toast.makeText(MainActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


After adding this code to your app. Now go to Firebase and click on Go to console option which is on 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 Realtime Database in the left window.   

After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. 

In this project, we are adding our rules as true for reading as well as a write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.

Step 6: Adding data in Firebase Console 

Inside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the “+” option on the right side and click on that option. After clicking on that option. Add the data as added in the below image. Make sure to add “Data” in the Name field because we are setting our reference for Firebase as “Data” in our code on line 55. So we have to set it to “Data”. You can change your reference and also change it in the Database. Inside the value field, you can add any data you want. This will be the string which we are going to display inside our text view. After adding data click on the add button and your data will be added in Firebase and this data will be displayed in your app. 

After adding this data you will get to see the below screen:  

After adding this data run your app and see the output of the app:

Output: 

While testing your app you can change your value field in your Firebase console and you can get to see that it will also get updated in your app as well. So in this task, we do not have to refresh our app any time. As soon as we update the value in our Firebase it will get updated in our App as well. In the below video we have changed the data from Firebase and it is being updated in-app as well. 
 

 



Last Updated : 02 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads