Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🔍 Overview
Every app needs a place to store and sync data, and Firebase
offers two powerful NoSQL cloud database options—Realtime Database and Cloud
Firestore. Both provide flexible, scalable data solutions with seamless
integration into mobile and web apps. This chapter compares the two,
demonstrates how to use them, and helps you decide which to choose for your
project.
🧠 Key Concepts
🔁 Realtime Database vs.
Firestore: Comparison Table
Feature |
Realtime Database |
Cloud Firestore |
Data Structure |
JSON tree |
Collections &
documents |
Querying |
Limited |
Advanced
filtering & compound queries |
Offline Support |
Yes (basic) |
Yes (more advanced) |
Scaling |
Limited
(shards needed for large data) |
Scales automatically |
Pricing Model |
Based on bandwidth
& data |
Based on reads, writes
& storage |
Real-Time Sync |
Excellent |
Excellent |
Region Replication |
No |
Yes (multi-region
support) |
Best Use Case |
Chat, live
tracking, small apps |
Complex apps,
data filtering, analytics |
🔧 Setting Up Firebase
Database Services
🔹 Step 1: Enable the
Database in Firebase Console
🔗 Firebase SDK Setup
(Java for Android)
groovy
dependencies
{
implementation
'com.google.firebase:firebase-database:20.3.0' // Realtime DB
implementation
'com.google.firebase:firebase-firestore:24.7.0' // Firestore
}
📘 Using Firebase Realtime
Database
🔹 Saving Data
java
DatabaseReference
dbRef = FirebaseDatabase.getInstance().getReference("users");
User
user = new User("Alice", "alice@example.com");
dbRef.push().setValue(user);
🔹 Reading Data
java
dbRef.addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot
snapshot) {
for (DataSnapshot userSnapshot :
snapshot.getChildren()) {
User user =
userSnapshot.getValue(User.class);
}
}
@Override
public void onCancelled(DatabaseError
error) {
Log.w("FirebaseDB",
"loadPost:onCancelled", error.toException());
}
});
🔹 Updating Data
java
dbRef.child("userId123").child("email").setValue("newemail@example.com");
🔹 Realtime DB Use Case:
Chat Application
JSON Tree Example:
json
"chats":
{
"room1": {
"message1": {
"sender": "John",
"text": "Hello"
},
"message2": {
"sender": "Jane",
"text": "Hi!"
}
}
}
🔥 Using Cloud Firestore
🔹 Creating and Writing to
a Document
java
FirebaseFirestore
db = FirebaseFirestore.getInstance();
Map<String,
Object> user = new HashMap<>();
user.put("name",
"Bob");
user.put("email",
"bob@example.com");
db.collection("users").add(user);
🔹 Reading Documents
java
db.collection("users").get()
.addOnSuccessListener(querySnapshot -> {
for (DocumentSnapshot doc :
querySnapshot) {
Log.d("Firestore",
doc.getId() + " => " + doc.getData());
}
});
🔹 Updating a Document
java
db.collection("users").document("userId123")
.update("email",
"updated@example.com");
🔹 Firestore Use Case:
E-Commerce Product Catalog
Firestore Structure Example:
bash
users/
userId123/
name: "Sara"
email: "sara@example.com"
products/
prod001/
title: "Shoes"
price: 49.99
orders/
order789/
userId: "userId123"
items: ["prod001",
"prod002"]
📊 Querying in Firestore
java
db.collection("products")
.whereEqualTo("category",
"shoes")
.orderBy("price",
Query.Direction.ASCENDING)
.get()
.addOnSuccessListener(querySnapshot -> {
for (DocumentSnapshot doc :
querySnapshot) {
Log.d("Product",
doc.getId() + " => " + doc.getData());
}
});
🔒 Securing Your Data:
Firebase Rules
🔹 Realtime DB Rule
json
{
"rules": {
".read": "auth !=
null",
".write": "auth !=
null"
}
}
🔹 Firestore Rule
js
rules_version
= '2';
service
cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid ==
userId;
}
}
}
🌐 Offline Support
Both databases support offline capabilities:
java
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Firestore enables it automatically on mobile.
🧩 Choosing Between
Realtime DB and Firestore
App Needs |
Best Option |
Simple JSON storage |
Realtime Database |
Structured, relational-style data |
Firestore |
Advanced queries |
Firestore |
Heavy real-time sync for chat |
Realtime
Database |
Offline-first apps |
Firestore |
Global-scale production |
Firestore |
✅ Best Practices
🧪 Testing and Debugging
📌 Conclusion
Both Firebase Realtime Database and Firestore offer
real-time, cloud-hosted NoSQL solutions that eliminate the need for traditional
backend setup. Firestore is the newer, more structured option with powerful
querying and scalability, while Realtime DB remains useful for ultra-fast
syncing in simpler apps.
In the next chapter, we’ll explore Firebase Cloud Functions and how to automate server-side tasks and event-driven logic.
BackFirebase is a Backend-as-a-Service (BaaS) platform by Google that offers a suite of tools like real-time databases, authentication, cloud storage, hosting, and analytics—enabling developers to build fully functional mobile apps without managing servers.
Yes, Firebase supports Android, iOS, and even cross-platform frameworks like Flutter and React Native, offering SDKs and libraries that make integration smooth across platforms.
Realtime Database is a low-latency JSON-based database ideal for syncing data in real-time. Firestore, on the other hand, is more scalable, supports structured collections/documents, and offers more advanced querying and offline support.
Absolutely. Firebase Authentication supports email/password, phone number, and social logins with built-in security, encrypted data transmission, and session management.
Yes, through Firebase Cloud Functions, you can write server-side logic (like sending notifications, validating data, or processing payments) that runs in response to events—all without managing physical servers.
Firebase offers a free-tier plan (Spark Plan) which includes many core features. As your usage grows, you can switch to the Blaze Plan (pay-as-you-go), which scales with your app's needs.
Firebase is built on Google Cloud infrastructure, making it highly scalable. Cloud Firestore and Cloud Functions scale automatically based on usage, ideal for apps with growing user bases.
Yes, Firebase is modular. You can use only the features you need—like Authentication or Cloud Messaging—without being forced to use the whole stack.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)