Day 25: Firebase Setup in Android – Realtime Database

🔥 What is Firebase?

Firebase is Google’s mobile development platform that offers backend services like Realtime Database, Authentication, Cloud Firestore, Crashlytics, Analytics, and more — eliminating the need for you to build a backend.

Infographic showing steps to integrate Firebase Authentication and Realtime Database in Android appsInfographic showing steps to integrate Firebase Authentication and Realtime Database in Android apps

🚀 Why Use Firebase?

  • Realtime data sync
  • Easy authentication (Email, Google, Phone, etc.)
  • Secure with built-in rules
  • No backend server needed
  • Supports Android, iOS, and Web

⚙️ Step 1: Create Firebase Project

  1. Go to Firebase Console
  2. Click Add project
  3. Name it e.g., HandsOnAndroid
  4. Disable Google Analytics (optional)
  5. Click Create project

📱 Step 2: Register Your App

  1. Click Android icon
  2. Enter package name (e.g., com.handsonandroid.app)
  3. Download google-services.json
  4. Place it in app/ directory

🧩 Step 3: Add Firebase SDK to Android App

In your build.gradle.kts (project level):

classpath("com.google.gms:google-services:4.4.0")

In your build.gradle.kts (app level):

plugins {
id("com.google.gms.google-services")
}

dependencies {
implementation("com.google.firebase:firebase-auth-ktx")
implementation("com.google.firebase:firebase-database-ktx")
}

Then sync the project.


🔐 Step 4: Enable Firebase Authentication

  1. Go to Firebase Console → Authentication
  2. Click Sign-in method
  3. Enable Email/Password
Diagram showing Firebase Auth and Realtime Database flow with Kotlin code blocks and app UI flow

🧪 Sample: Firebase Auth (Email/Password)

fun signUpUser(email: String, password: String) {
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("FirebaseAuth", "User created: ${task.result.user?.uid}")
} else {
Log.e("FirebaseAuth", "Signup failed", task.exception)
}
}
}

💾 Step 5: Enable Realtime Database

  1. Go to Realtime Database
  2. Click Create Database
  3. Choose location
  4. Set rules:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}

💡 Sample: Write to Realtime Database

fun writeUserData(userId: String, name: String, email: String) {
val user = mapOf("name" to name, "email" to email)
FirebaseDatabase.getInstance()
.getReference("users")
.child(userId)
.setValue(user)
}

🔎 Sample: Read from Realtime Database

fun fetchUserData(userId: String) {
FirebaseDatabase.getInstance()
.getReference("users/$userId")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val name = snapshot.child("name").value.toString()
val email = snapshot.child("email").value.toString()
Log.d("FirebaseDB", "User: $name, Email: $email")
}

override fun onCancelled(error: DatabaseError) {
Log.e("FirebaseDB", "Read failed", error.toException())
}
})
}

✅ Best Practices

  • Use a repository pattern for Firebase interaction
  • Handle errors gracefully
  • Secure rules using auth.uid == request.auth.uid
  • Monitor with Firebase Analytics

🔗 Internal Links

🔑 Key Points

  1. What is Firebase?
    Firebase is a Backend-as-a-Service (BaaS) that offers tools like Realtime Database, Authentication, and Analytics for building powerful Android apps quickly.
  2. Firebase Setup in Android
    • Create a Firebase project at console.firebase.google.com.
    • Register your Android app with the package name.
    • Download google-services.json and add it to the app/ directory.
    • Add the Firebase SDK and google-services plugin in build.gradle.
  3. Firebase Authentication Basics
    • Enable authentication methods (email/password, Google, etc.) in Firebase Console.
    • Use FirebaseAuth for login, registration, and managing users.
  4. Realtime Database Basics
    • A NoSQL cloud database for syncing data across clients in real-time.
    • Structure your data with JSON format.
    • Use DatabaseReference to read/write data.
  5. Sample Code for Firebase Auth kotlinCopyEditFirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { val user = FirebaseAuth.getInstance().currentUser } }
  6. Sample Code for Realtime DB kotlinCopyEditval dbRef = FirebaseDatabase.getInstance().getReference("users") dbRef.child(userId).setValue(User(name, email))
  7. Common Pitfalls
    • Don’t forget internet permission.
    • Always check for null values in authentication and database callbacks.
    • Handle security rules correctly to avoid unauthorized access.
  8. Security Rules Basics
    • Use .read and .write rules to control access.
    • Test with Firebase Emulator for safer development.
  9. Useful Firebase Tools
    • Firebase Emulator Suite for offline/local testing
    • Firebase Analytics for event tracking
    • Crashlytics for real-time crash reports
Infographic showing steps to integrate Firebase Authentication and Realtime Database in Android apps

❓ FAQ

Q: Is Firebase Realtime Database free?

Yes, it has a generous free tier (Spark Plan).

Q: What’s the difference between Realtime Database and Firestore?

Firestore is newer and more scalable. Realtime DB is simple and good for smaller apps.

Q: Can I use Firebase with Jetpack Compose?

Yes, Firebase works with both XML and Jetpack Compose apps.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top