Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Delete Data from Firebase Realtime Database in Android?
Next article icon

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

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
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 both Java and Kotlin 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 and Connect to Firebase app

Refer to Adding firebase to android app and follow the steps to connect firebase to your project.

Step 2: Add Realtime Database to you app in Console

- Go to Firebase console and navigate to your project, and on the left side of the screen, under Build choose Realtime Database. On the next screen, select Create Database.

- On the dialog box that appears, choose a Realtime Database Location and click on Next. Then select Start in locked mode and click on Enable. You can't change the Realtime Database Location later, so be careful while choosing.

Now, in Realtime Database, under Rules make the following changes:

Step 3: Add Realtime Database to you app in Android Studio

Navigate to Tools > Firebase. This will open the Firebase Assistant tab. Now select Realtime Database > Get started with Realtime Database.

Now select Add the Realtime Database SDK to your app, then select Accept Changes in the dialog box. This will add all the necessary dependencies for realtime database.

Step 4: Add necessary permissions

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

Step 5: Create a model class for User Info

Right click on app and select New > Kotlin/Java class file and provide the name Person to the file. Add the following code to the file.

Person.java
package org.geeksforgeeks.demo;  public class Person {     private String name;     private String number;     private String address;      public Person() {}      public Person(String name, String number,                   String address)     {         this.name = name;         this.number = number;         this.address = address;     }      public String getName() { return name; }      public void setName(String name) { this.name = name; }      public String getNumber() { return number; }      public void setNumber(String number)     {         this.number = number;     }      public String getAddress() { return address; }      public void setAddress(String address)     {         this.address = address;     } } 
Person.kt
package org.geeksforgeeks.demo  class Person (     var name: String? = null,     var number: String? = null,     var address: String? = null ) 

Step 6: Working with MainActivity and it's layout file

In the previous article, How to Save Data to the Firebase Realtime Database in Android?, we learned how to save data in realtime database. In this article, we will retrieve the same data that we saved in the previous article. Refer to the image below to check the data we saved.


Navigate to app > java > package name > MainActivity and app > res > layout > activity_main.xml. Then add the following code to the MainActivity file in Java or Koltin and the xml code to the activity_main.xml file.

MainActivity.java
package org.geeksforgeeks.demo;  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.*;  public class MainActivity extends AppCompatActivity {      private TextView nameTextView, phoneTextView, addressTextView;     private FirebaseDatabase firebaseDatabase;     private DatabaseReference databaseReference;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          nameTextView = findViewById(R.id.nameTextView);         phoneTextView = findViewById(R.id.phoneTextView);         addressTextView = findViewById(R.id.addressTextView);          firebaseDatabase = FirebaseDatabase.getInstance();         databaseReference = firebaseDatabase.getReference("PersonData");          retrieveFirstDataFromFirebase();     }      private void retrieveFirstDataFromFirebase() {         databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {             @Override             public void onDataChange(@NonNull DataSnapshot snapshot) {                 for (DataSnapshot dataSnapshot : snapshot.getChildren()) {                     Person person = dataSnapshot.getValue(Person.class);                     if (person != null) {                         nameTextView.setText("Name: " + person.getName());                         phoneTextView.setText("Phone: " + person.getNumber());                         addressTextView.setText("Address: " + person.getAddress());                         break;                     }                 }             }              @Override             public void onCancelled(@NonNull DatabaseError error) {                 Toast.makeText(MainActivity.this, "Failed to retrieve data: " + error.getMessage(), Toast.LENGTH_SHORT).show();             }         });     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.*  class MainActivity : AppCompatActivity() {      private lateinit var nameTextView: TextView     private lateinit var phoneTextView: TextView     private lateinit var addressTextView: TextView     private lateinit var firebaseDatabase: FirebaseDatabase     private lateinit var databaseReference: DatabaseReference      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          nameTextView = findViewById(R.id.nameTextView)         phoneTextView = findViewById(R.id.phoneTextView)         addressTextView = findViewById(R.id.addressTextView)          firebaseDatabase = FirebaseDatabase.getInstance()         databaseReference = firebaseDatabase.getReference("PersonData")          retrieveFirstDataFromFirebase()     }      private fun retrieveFirstDataFromFirebase() {         databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {             override fun onDataChange(snapshot: DataSnapshot) {                 for (dataSnapshot in snapshot.children) {                     val person = dataSnapshot.getValue(Person::class.java)                     person?.let {                         nameTextView.text = "Name: ${it.name}"                         phoneTextView.text = "Phone: ${it.number}"                         addressTextView.text = "Address: ${it.address}"                     }                     break                 }             }              override fun onCancelled(error: DatabaseError) {                 Toast.makeText(this@MainActivity, "Failed to retrieve data: ${error.message}", Toast.LENGTH_SHORT).show()             }         })     } } 
activity_main.xml
<LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     xmlns:tools="http://schemas.android.com/tools"     android:orientation="vertical"     android:gravity="center"     android:padding="32dp"     tools:context=".MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Retrieved Data"         android:textSize="18sp"         android:textStyle="bold"         android:paddingBottom="10dp"/>      <TextView         android:id="@+id/nameTextView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Name: "         android:textSize="16sp"/>      <TextView         android:id="@+id/phoneTextView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Phone: "         android:textSize="16sp"/>      <TextView         android:id="@+id/addressTextView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Address: "         android:textSize="16sp"/> </LinearLayout> 

Output:

retrieve-data-firebase



Next Article
How to Delete Data from Firebase Realtime Database in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Kotlin Android
  • Java-Android
  • Firebase-Android
Practice Tags :
  • Java

Similar Reads

  • 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 o
    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 simp
    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
    8 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 ite
    4 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 Databa
    8 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 o
    4 min read
  • How to Upload Excel/Google 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
    11 min read
  • How to Read Data from SQLite Database in Android?
    In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
    12 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 f
    8 min read
  • How to Read Data from Realm Database in Android?
    In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app.  What we are going to build in this article?  In this article, we will be simply adding a Button to open a new act
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences