Firebase

Backend-as-a-Service for auth, databases, storage, and push messaging

Auth Firestore Storage FCM

Table of Contents

Firebase Overview

Firebase is Google's mobile and web development platform providing backend services — authentication, NoSQL databases, file storage, analytics, and cloud messaging — without managing your own servers.

Android App ↓ Firebase SDK (Auth, Firestore, Storage, FCM) ↓ Google Cloud Firebase Backend
ServicePurposeWhen to Use
AuthenticationUser sign-inEmail, Google, phone login
Realtime DatabaseJSON tree, live syncChat, live scores, simple sync
Cloud FirestoreDocument/collection NoSQLMost new apps (recommended)
StorageFile uploadsImages, videos, PDFs
Cloud Messaging (FCM)Push notificationsAlerts, re-engagement

1Firebase Setup

Connect your Android app to a Firebase project in a few steps. The Firebase console generates a google-services.json config file that links your app to backend services.

Step-by-step setup

  1. Go to console.firebase.google.com
  2. Create a project (or use an existing one)
  3. Click Add app → Android
  4. Enter package name (e.g. com.example.myapp)
  5. Download google-services.json → place in app/ module root
  6. Enable desired services in Firebase Console (Auth, Firestore, etc.)

Project-level Gradle

Kotlin — build.gradle.kts (project root)plugins { id("com.google.gms.google-services") version "4.4.1" apply false }

App-level Gradle

Kotlin — app/build.gradle.ktsplugins { id("com.android.application") id("org.jetbrains.kotlin.android") id("com.google.gms.google-services") } dependencies { implementation(platform("com.google.firebase:firebase-bom:32.7.2")) implementation("com.google.firebase:firebase-auth-ktx") implementation("com.google.firebase:firebase-firestore-ktx") implementation("com.google.firebase:firebase-database-ktx") implementation("com.google.firebase:firebase-storage-ktx") implementation("com.google.firebase:firebase-messaging-ktx") }

Initialize Firebase (optional explicit init)

Kotlin — MyApplication.ktclass MyApplication : Application() { override fun onCreate() { super.onCreate() FirebaseApp.initializeApp(this) } }

2Authentication

Firebase Authentication supports email/password, Google Sign-In, phone OTP, and more. It handles secure token management and integrates with Firestore security rules.

Email/password sign up and login

Kotlin — AuthRepository.ktclass AuthRepository { private val auth = FirebaseAuth.getInstance() val currentUser: FirebaseUser? get() = auth.currentUser val isLoggedIn: Boolean get() = currentUser != null suspend fun signUp(email: String, password: String): Result<FirebaseUser> { return try { val result = auth.createUserWithEmailAndPassword(email, password).await() Result.success(result.user!!) } catch (e: Exception) { Result.failure(e) } } suspend fun signIn(email: String, password: String): Result<FirebaseUser> { return try { val result = auth.signInWithEmailAndPassword(email, password).await() Result.success(result.user!!) } catch (e: Exception) { Result.failure(e) } } fun signOut() = auth.signOut() }

Login Activity usage

Kotlin — LoginActivity.ktclass LoginActivity : AppCompatActivity() { private val authRepo = AuthRepository() private fun login() { val email = binding.etEmail.text.toString().trim() val password = binding.etPassword.text.toString() lifecycleScope.launch { binding.btnLogin.isEnabled = false val result = authRepo.signIn(email, password) binding.btnLogin.isEnabled = true result.onSuccess { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() }.onFailure { e -> Toast.makeText(this@LoginActivity, e.message, Toast.LENGTH_SHORT).show() } } } }

Auth state listener

Kotlin — Observe login stateprivate var authListener: FirebaseAuth.AuthStateListener? = null override fun onStart() { super.onStart() authListener = FirebaseAuth.AuthStateListener { auth -> if (auth.currentUser == null) { startActivity(Intent(this, LoginActivity::class.java)) finish() } } FirebaseAuth.getInstance().addAuthStateListener(authListener!!) } override fun onStop() { authListener?.let { FirebaseAuth.getInstance().removeAuthStateListener(it) } super.onStop() }

3Realtime Database

Firebase Realtime Database stores data as a JSON tree and syncs changes to all connected clients in milliseconds — ideal for chat apps and live leaderboards.

Write and read data

Kotlin — Realtime Database CRUDclass ChatRepository { private val database = FirebaseDatabase.getInstance() private val messagesRef = database.getReference("messages") fun sendMessage(userId: String, text: String) { val key = messagesRef.push().key ?: return val message = mapOf( "id" to key, "userId" to userId, "text" to text, "timestamp" to ServerValue.TIMESTAMP ) messagesRef.child(key).setValue(message) } fun listenForMessages(onMessages: (List<ChatMessage>) -> Unit) { messagesRef.orderByChild("timestamp").addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val messages = snapshot.children.mapNotNull { child -> child.getValue(ChatMessage::class.java) } onMessages(messages) } override fun onCancelled(error: DatabaseError) { Log.e("RTDB", "Listen failed", error.toException()) } }) } } data class ChatMessage( val id: String = "", val userId: String = "", val text: String = "", val timestamp: Long = 0 )

JSON structure example

JSON — Realtime Database tree{ "messages": { "msg001": { "id": "msg001", "userId": "user_42", "text": "Hello Firebase!", "timestamp": 1717000000000 } }, "users": { "user_42": { "name": "Nikhil", "online": true } } }

Firestore vs Realtime Database: Prefer Firestore for new projects (better queries, scaling, offline). Use Realtime Database when you need ultra-low-latency sync with a simple JSON tree.

4Firestore

Cloud Firestore is a flexible, scalable NoSQL document database. Data is organized in collections and documents with powerful querying and offline support.

Add, read, update, delete

Kotlin — FirestoreRepository.ktclass FirestoreRepository { private val db = FirebaseFirestore.getInstance() private val usersRef = db.collection("users") suspend fun addUser(user: User): String { val docRef = usersRef.add(user).await() return docRef.id } suspend fun getUser(userId: String): User? { val snapshot = usersRef.document(userId).get().await() return snapshot.toObject(User::class.java) } suspend fun updateUser(userId: String, name: String) { usersRef.document(userId) .update("name", name, "updatedAt", FieldValue.serverTimestamp()) .await() } suspend fun deleteUser(userId: String) { usersRef.document(userId).delete().await() } } data class User( val name: String = "", val email: String = "", val createdAt: Timestamp? = null )

Real-time listener with Flow

Kotlin — Observe collection changesfun observeTodos(): Flow<List<Todo>> = callbackFlow { val listener = db.collection("todos") .orderBy("createdAt", Query.Direction.DESCENDING) .addSnapshotListener { snapshot, error -> if (error != null) { close(error) return@addSnapshotListener } val todos = snapshot?.documents?.mapNotNull { it.toObject(Todo::class.java)?.copy(id = it.id) } ?: emptyList() trySend(todos) } awaitClose { listener.remove() } }

Query with filters

Kotlin — Firestore queriessuspend fun getCompletedTodos(): List<Todo> { val snapshot = db.collection("todos") .whereEqualTo("completed", true) .whereGreaterThan("priority", 2) .orderBy("priority", Query.Direction.DESCENDING) .limit(20) .get() .await() return snapshot.documents.mapNotNull { it.toObject(Todo::class.java) } }

5Firebase Storage

Firebase Storage stores user-generated files — profile photos, documents, videos — with security rules tied to Firebase Authentication.

Upload image file

Kotlin — StorageRepository.ktclass StorageRepository { private val storage = FirebaseStorage.getInstance() private val imagesRef = storage.reference.child("profile_images") suspend fun uploadProfileImage(userId: String, imageUri: Uri): Result<String> { return try { val fileRef = imagesRef.child("$userId.jpg") fileRef.putFile(imageUri).await() val downloadUrl = fileRef.downloadUrl.await().toString() Result.success(downloadUrl) } catch (e: Exception) { Result.failure(e) } } suspend fun deleteProfileImage(userId: String): Result<Unit> { return try { imagesRef.child("$userId.jpg").delete().await() Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } }

Upload with progress

Kotlin — Monitor upload progressfun uploadWithProgress(userId: String, uri: Uri, onProgress: (Int) -> Unit) { val fileRef = FirebaseStorage.getInstance() .reference.child("uploads/$userId/${System.currentTimeMillis()}.jpg") val uploadTask = fileRef.putFile(uri) uploadTask.addOnProgressListener { snapshot -> val progress = (100.0 * snapshot.bytesTransferred / snapshot.totalByteCount).toInt() onProgress(progress) }.addOnSuccessListener { fileRef.downloadUrl.addOnSuccessListener { downloadUri -> Log.d("Storage", "Uploaded: $downloadUri") } }.addOnFailureListener { e -> Log.e("Storage", "Upload failed", e) } }

Basic Storage security rules

Firebase Console — storage.rulesrules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /profile_images/{userId}.jpg { allow read: if request.auth != null; allow write: if request.auth != null && request.auth.uid == userId; } } }

6Push Notifications

Firebase Cloud Messaging (FCM) delivers push notifications to Android devices. Messages can be sent from the Firebase Console, your backend server, or Cloud Functions.

FirebaseMessagingService

Kotlin — MyFirebaseMessagingService.ktclass MyFirebaseMessagingService : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { super.onMessageReceived(message) val title = message.notification?.title ?: message.data["title"] ?: "Notification" val body = message.notification?.body ?: message.data["body"] ?: "" showNotification(title, body, message.data) } override fun onNewToken(token: String) { super.onNewToken(token) Log.d("FCM", "Refreshed token: $token") sendRegistrationToServer(token) } private fun showNotification(title: String, body: String, data: Map<String, String>) { val channelId = "fcm_default" val intent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP data.forEach { (key, value) -> putExtra(key, value) } } val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .build() NotificationManagerCompat.from(this).notify(System.currentTimeMillis().toInt(), notification) } }

Manifest and get token

XML — AndroidManifest.xml<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
Kotlin — Get FCM tokenFirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (task.isSuccessful) { val token = task.result Log.d("FCM", "Token: $token") // Save to Firestore under users/{uid}/fcmToken } }

Send from Firebase Console

  1. Firebase Console → Engage → Messaging
  2. Click Create campaign → Notifications
  3. Enter title, body, and target (all users or topic)
  4. Publish — devices with your app receive the notification

Data vs notification payload

Payload TypeHandled ByWhen App in Background
notificationSystem tray automaticallySystem shows notification
dataonMessageReceived()Your code handles display
BothSystem + your handlerSystem shows; tap opens app with data

7Hands-On Exercises

1

Create a Firebase project, add your Android app, and complete Firebase Setup with BOM dependencies.

2

Build email/password sign up and login screens. Redirect to MainActivity when authenticated.

3

Create a simple chat using Realtime Database — send messages and display them in real time.

4

Build a todo app with Firestore: add, list, mark complete, and delete todos with a real-time listener.

5

Upload a profile photo to Firebase Storage and save the download URL in the user's Firestore document.

6

Implement FCM: log the device token, handle incoming messages in FirebaseMessagingService, and show a local notification.

7

Bonus: Send a test push from Firebase Console and verify the notification appears on your device.

Firebase MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Firebase MCQs

1

Firebase is?

ALinux kernel fork
BGoogle mobile/backend platform (BaaS)
CLayout editor
DGradle replacement
Explanation: Auth, Firestore, Storage, FCM, Analytics, and more.
2

google-services.json placed in?

Aassets only
BManifest folder
CApp module root directory
DGradle wrapper
Explanation: Downloaded from Firebase console per app.
3

Firebase Authentication supports?

ACamera only
BSQL only
CBluetooth only
DEmail, Google, phone, anonymous
Explanation: Multiple sign-in providers via Firebase Auth SDK.
4

Cloud Firestore stores?

ANoSQL document data in collections
BRelational SQL tables locally only
CAPK files
DLayout XML
Explanation: Documents in collections with real-time sync.
5

Realtime Database vs Firestore?

AIdentical
BFirestore newer with richer queries and scaling
CRTDB only option
DBoth SQL
Explanation: Firestore recommended for new projects.
6

Firebase Storage for?

ADex files
BLocal SQLite
CUser files — images, videos in cloud
DEmulator images
Explanation: Backed by Google Cloud Storage buckets.
7

FCM token used to?

ALayout preview
BSign APK
CCompile Kotlin
DTarget device for push messages
Explanation: Server sends messages to device token via FCM API.
8

Firebase BOM in Gradle?

ABill of Materials aligning Firebase library versions
BBinary APK
CManifest merge tool
DLint rule
Explanation: implementation platform('com.google.firebase:firebase-bom')
9

Anonymous auth useful for?

AProduction admin only
BGuest users before full sign-up
CBanned by Google
DReplaces Firestore
Explanation: Upgrade linking to permanent account later.
10

Firestore security rules?

AProGuard
BUI themes
CServer-side access control on database reads/writes
DADB rules
Explanation: Rules in Firebase console define who can read/write data.

10 Advanced Firebase MCQs

11

Firestore offline persistence?

ADisabled always
BCached locally; syncs when online
CSQL only
DNo cache
Explanation: enablePersistence or default enabled on Android.
12

FirebaseAuth signOut?

AClear Gradle cache
BDelete google-services.json
CFirebaseAuth.getInstance().signOut()
DUninstall app
Explanation: Also revoke tokens provider-specific if needed.
13

Storage upload task?

AIntent filter
BSynchronous only
CRoom insert
DstorageRef.putFile(uri) returns Task with progress
Explanation: Monitor addOnSuccessListener and addOnFailureListener.
14

Firestore composite index needed when?

ACompound inequality queries on multiple fields
BSingle field equality only
CNever
DAll queries
Explanation: Console link in error message creates required index.
15

Firebase Emulator Suite?

AProduction only
BLocal emulators for Auth, Firestore, Functions testing
CReplaces Android Studio
DGPS simulator
Explanation: Connect SDK to localhost emulators during dev.
16

IdToken from Firebase user?

AAPK signature
BLayout ID
CJWT for backend authentication verification
DSensor ID
Explanation: Send token to your server; verify with Firebase Admin SDK.
17

Firestore transaction?

ACamera bind
BUI animation
CBluetooth pair
DAtomic read-write on multiple documents
Explanation: runTransaction ensures consistency for counters etc.
18

Dynamic Links (deprecated direction)?

ABeing replaced — use App Links / Play Install Referrer
BOnly Firebase feature
CRequired
DSQL migration
Explanation: Check current Google guidance for deep linking.
19

Firebase Crashlytics?

ADatabase
BCrash reporting and analytics
CPush only
DCamera
Explanation: Log non-fatal errors and custom keys for debugging production.
20

Security rules test?

AImpossible
BProduction only
CRules Playground in console or emulator unit tests
DManifest lint
Explanation: Never ship open allow read, write: if true rules.
Click an option to select, then check answers.

Firebase Interview Q&A

15 topic-focused questions for interviews and revision.

1Steps to add Firebase to Android app.easy
Answer: Create Firebase project, add Android app with package name, download google-services.json, apply google-services plugin, add BOM dependencies.
2Email/password sign up flow.easy
Answer: FirebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener { ... }
3Write document to Firestore.easy
Answer: db.collection("users").document(uid).set(mapOf("name" to name))
4Read Firestore with listener.medium
Answer: addSnapshotListener on DocumentReference or Query — receives real-time updates.
5Upload image to Firebase Storage.medium
Answer: storage.reference.child("images/$uid.jpg").putFile(uri)
6Receive FCM message.medium
Answer: Extend FirebaseMessagingService, override onMessageReceived, show notification if needed.
7Firestore vs Realtime Database choose.medium
Answer: Firestore: richer queries, scalability, offline. RTDB: simpler tree, lower latency sometimes legacy apps.
8Secure Firestore data.hard
Answer: Auth-required rules: allow read, write: if request.auth != null && request.auth.uid == userId;
9Get FCM registration token.medium
Answer: FirebaseMessaging.getInstance().token.addOnCompleteListener { token -> sendToServer(token) }
10Handle auth state across app.easy
Answer: FirebaseAuth.addAuthStateListener { if (user == null) navigate login else main }
11Offline Firestore behavior.medium
Answer: Reads/writes queue locally; sync when connection restored; listeners fire cached data first.
12Firebase Analytics.easy
Answer: Automatic events + logEvent for custom funnels; BigQuery export optional.
13Link anonymous to email account.hard
Answer: linkWithCredential(EmailAuthProvider.getCredential(email, pass)) on current user.
14Storage download URL.medium
Answer: After upload, snapshot.storage.downloadUrl.await() for public link with token.
15Common Firebase setup error.easy
Answer: Package name mismatch in console vs applicationId; missing google-services plugin apply.