Connecting an Android Project to Firebase
Course: Android App Development
Topic: Connecting an Android Project to Firebase
Course Link: Android App Development Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Firebase
Firebase is a development platform from Google that provides backend services and tools for building mobile and web applications. It helps Android developers implement authentication, cloud data storage, file uploads, push notifications, analytics, crash reporting, and other features without having to build every backend component from scratch.
Connecting an Android project to Firebase means registering the application with a Firebase project, adding the appropriate configuration file and Gradle dependencies, and initializing the Firebase SDK so the application can communicate with the selected Firebase services.
For example, a student management application can use Firebase Authentication to sign students in and Cloud Firestore to store student profiles and course information.
2. Learning Objectives
- Understand Firebase and its role in Android development.
- Learn the major Firebase services available for Android applications.
- Create a Firebase project using the Firebase Console.
- Register an Android application with Firebase.
- Configure google-services.json and the Google Services Gradle plugin.
- Add Firebase SDK dependencies using the Firebase Android BoM.
- Connect an Android application to Firebase Authentication.
- Store and retrieve data using Cloud Firestore.
- Understand security rules, troubleshooting, and testing.
- Build a practical Android application integrated with Firebase.
3. What Is Firebase?
Firebase provides managed services that help developers build applications with less backend infrastructure work. It integrates with Android Studio and the Android SDK ecosystem.
Important Firebase services
| Service |
Purpose |
Example Use Case |
| Firebase Authentication |
Manages user authentication |
Email and password sign-in |
| Cloud Firestore |
Stores structured application data in a cloud database |
User profiles and course records |
| Realtime Database |
Provides a cloud-hosted database with realtime synchronization |
Live status updates |
| Cloud Storage |
Stores files such as images and documents |
Profile pictures and uploaded documents |
| Firebase Cloud Messaging |
Delivers push messages to supported clients |
Course announcements |
| Firebase Analytics |
Measures application usage and events |
Tracking screen visits |
| Firebase Crashlytics |
Reports application crashes and related diagnostics |
Investigating production crashes |
| Remote Config |
Controls selected application behavior through remotely managed parameters |
Changing a feature flag |
4. Why Connect an Android Project to Firebase?
- Backend integration: Connect the application to cloud services without creating every server component yourself.
- User authentication: Support sign-in providers such as email and password.
- Cloud database: Store and retrieve application data from multiple devices.
- Realtime updates: Observe data changes through supported Firebase services.
- Application monitoring: Collect analytics and crash reports when configured.
- Scalable development: Use managed infrastructure that can grow with application requirements and configured service limits.
5. Prerequisites
Before connecting Firebase, prepare the following:
- Android Studio installed and updated.
- An Android project that builds successfully.
- A Google account with access to the Firebase Console.
- A valid Android application ID or package name.
- An internet connection for setup and cloud operations.
- An Android emulator or physical device for testing.
- Gradle configuration compatible with the Firebase SDKs being used.
Check the current Firebase Android setup documentation for minimum SDK, Android Gradle Plugin, and other compatibility requirements before choosing library versions.
6. Step 1: Create a Firebase Project
A Firebase project is the central container for your registered applications, configuration, and Firebase services.
- Open the Firebase Console.
- Sign in with your Google account.
- Click the option to create a project or add a Firebase project.
- Enter a meaningful project name, such as AndroidStudentApp.
- Follow the prompts and review the available Google Analytics setup options.
- Click the project creation button and wait for the setup to finish.
- Open the Firebase project dashboard.
Important: The project display name is not necessarily the same as the unique Firebase project ID. Keep track of the correct project when connecting multiple applications.
7. Step 2: Register Your Android Application
Registering your Android application tells Firebase which application belongs to the Firebase project.
- Open your project dashboard in the Firebase Console.
- Click the Android icon or select Add app.
- Find the application ID in your Android project's module-level Gradle configuration.
- Enter the exact application ID in the Android package name field.
- Optionally provide an app nickname.
- Click Register app.
Example application ID
com.example.studentapp
The package name or application ID must match the application you are building. It is case-sensitive, and the registered Firebase Android app's package name cannot be changed afterward. If you need a different application ID, register another Android app in Firebase.
8. Step 3: Download google-services.json
After registering the Android app, Firebase provides a configuration file named google-services.json.
- Download the configuration file from the Firebase Console.
- Open your Android project in Android Studio.
- Locate the app module's root directory.
- Copy google-services.json into that directory.
- Confirm that the filename is exactly google-services.json.
Expected project structure
AndroidProject/
├── settings.gradle.kts
├── build.gradle.kts
└── app/
├── build.gradle.kts
├── google-services.json
└── src/
└── main/
├── AndroidManifest.xml
└── java/
The configuration file contains project and application identifiers used by Firebase tooling. It is not a replacement for security rules, authentication, or authorization. Do not treat client-side Firebase configuration as a secret that secures your database.
9. Step 4: Configure the Google Services Gradle Plugin
The Google Services Gradle plugin processes google-services.json and makes the relevant Firebase configuration available to the Android application.
The following examples use Kotlin DSL Gradle files, identified by the .gradle.kts extension. If your project uses Groovy Gradle files, use the equivalent Groovy syntax instead.
Project-level build.gradle.kts
Add the Google Services plugin declaration to the project-level plugins block, using the version shown in the current official Firebase setup instructions:
plugins {
id("com.android.application") version "YOUR_AGP_VERSION" apply false
id("com.google.gms.google-services") version "4.5.0" apply false
}
Keep the Android Gradle Plugin version compatible with your project. Do not replace your existing working configuration blindly.
App-level app/build.gradle.kts
Apply the plugin in the application module:
plugins {
id("com.android.application")
id("com.google.gms.google-services")
}
If the plugins block already contains other plugins, keep them and add the Google Services plugin alongside them.
10. Step 5: Add Firebase Dependencies
Firebase offers separate Android libraries for its services. The Firebase Android BoM (Bill of Materials) manages compatible versions across Firebase libraries.
For example, to use Firebase Authentication and Cloud Firestore, add the following dependencies to the app module's build.gradle.kts file:
dependencies {
implementation(platform("com.google.firebase:firebase-bom:35.1.0"))
implementation("com.google.firebase:firebase-auth")
implementation("com.google.firebase:firebase-firestore")
}
The BoM version above is based on the official setup documentation available at the time these notes were prepared. Check the current Firebase release information when creating or upgrading a project. When using the BoM, do not specify individual versions for the Firebase libraries managed by it.
Only add the Firebase services your application needs. For example, if the application requires only authentication, you can start with the Authentication dependency and add Firestore later.
Additional dependency examples
// Analytics
implementation("com.google.firebase:firebase-analytics")
// Realtime Database
implementation("com.google.firebase:firebase-database")
// Cloud Storage
implementation("com.google.firebase:firebase-storage")
// Cloud Messaging
implementation("com.google.firebase:firebase-messaging")
// Crash reporting
implementation("com.google.firebase:firebase-crashlytics")
These are optional examples, not a list of dependencies that must all be added. Some products, such as Crashlytics, also require their corresponding Gradle plugin or additional setup.
11. Step 6: Synchronize the Gradle Project
After configuring the plugins and dependencies, synchronize your project.
- Save the Gradle files.
- Click Sync Now if Android Studio displays the synchronization prompt.
- Wait for dependency resolution and project configuration to finish.
- Resolve any compatibility or dependency errors.
- Build and run the application on a test device or emulator.
If the project synchronizes successfully, the required Firebase SDKs should be available to your Kotlin code.
12. Step 7: Initialize Firebase
In a standard Android setup, the Google Services plugin and Firebase configuration allow the Firebase SDK to initialize using the application's configured Firebase options. Many common services can then be accessed through their respective SDK entry points.
For example, Firebase Authentication can be accessed like this:
import com.google.firebase.auth.FirebaseAuth
val auth = FirebaseAuth.getInstance()
Most standard applications do not need to call FirebaseApp.initializeApp() manually when the Google Services plugin and configuration file are set up correctly. Manual initialization may be appropriate for special cases, such as applications that use multiple Firebase projects or custom Firebase options.
13. Example 1: Connect Firebase Authentication
Firebase Authentication supports user sign-in and account creation using configured identity providers. To use email and password authentication, first enable the provider in the Firebase Console.
Enable Email/Password authentication
- Open your Firebase project.
- Navigate to Authentication.
- Open the sign-in method or provider settings.
- Enable Email/Password.
- Save the changes.
Kotlin example: Create an account
import com.google.firebase.auth.FirebaseAuth
class AuthRepository {
private val auth: FirebaseAuth =
FirebaseAuth.getInstance()
fun registerUser(
email: String,
password: String,
onResult: (Boolean, String?) -> Unit
) {
auth.createUserWithEmailAndPassword(
email.trim(),
password
).addOnCompleteListener { task ->
if (task.isSuccessful) {
onResult(true, null)
} else {
onResult(
false,
task.exception?.localizedMessage
)
}
}
}
}
This example demonstrates the Firebase SDK call and returns the operation result to the caller. Connect it to a UI with appropriate validation and lifecycle-aware state handling. Never log passwords or expose sensitive authentication details in error messages.
Sign in an existing user
auth.signInWithEmailAndPassword(
email.trim(),
password
).addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = auth.currentUser
// Navigate to the authenticated screen.
} else {
// Show a safe, user-friendly error message.
}
}
Use a proper authentication flow in the real application. Validate input, provide loading feedback, handle errors, and protect screens that require a signed-in user.
14. Example 2: Connect Cloud Firestore
Cloud Firestore is a document database that organizes data into collections and documents. It supports queries, realtime listeners, and offline capabilities according to the SDK and database configuration.
Firestore data structure
students (collection)
└── student_001 (document)
├── name: "Aarav"
├── course: "Android Development"
└── active: true
Kotlin example: Save a student document
import com.google.firebase.firestore.FirebaseFirestore
class StudentRepository {
private val db = FirebaseFirestore.getInstance()
fun addStudent(
name: String,
course: String,
onResult: (Boolean, String?) -> Unit
) {
val student = hashMapOf(
"name" to name,
"course" to course,
"active" to true
)
db.collection("students")
.add(student)
.addOnSuccessListener {
onResult(true, null)
}
.addOnFailureListener { exception ->
onResult(
false,
exception.localizedMessage
)
}
}
}
This code creates a document with an automatically generated ID. Before using it, create or configure the Cloud Firestore database in the Firebase Console and define appropriate security rules.
Read student documents
db.collection("students")
.get()
.addOnSuccessListener { result ->
for (document in result) {
val name = document.getString("name")
val course = document.getString("course")
// Map the document to your application model.
}
}
.addOnFailureListener { exception ->
// Handle the read failure.
}
This example performs a one-time query. For live updates, use a snapshot listener and remove or scope the listener appropriately when the observing screen is no longer active.
15. Step 8: Configure Firebase Security Rules
Connecting an application to Firebase does not automatically make its database secure. Security rules determine which clients can read or write data, and authentication alone does not guarantee that a user is authorized to access a particular document.
Example development rule concept
A secure production rule should enforce the required identity, ownership, and data validation conditions. For example, user-specific documents can be restricted to the authenticated user whose UID matches the document ID.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write:
if request.auth != null
&& request.auth.uid == userId;
}
}
}
This example protects documents under the users collection by matching the authenticated user's UID with the document ID. It is not a complete rule set for every application; additional field validation and authorization may be required. Do not deploy open read/write rules to production.
16. Using Android Studio Firebase Assistant
Android Studio includes a Firebase Assistant workflow that can help connect an Android project to Firebase.
- Open the Android project in Android Studio.
- Open the Tools menu and select Firebase, if available.
- Choose the desired service, such as Authentication or Cloud Firestore.
- Follow the connection instructions provided in the Assistant.
- Allow the Assistant to register the app and configure the relevant files when supported.
- Add or verify the required SDK dependencies.
- Complete any service-specific setup in the Firebase Console.
The Assistant can simplify configuration, but always verify the resulting Gradle files, app registration, and Firebase security settings.
17. Testing the Firebase Connection
After configuration, test a real Firebase operation rather than assuming that a successful Gradle sync proves that every service is configured correctly.
- Build and launch the Android application.
- Check that Firebase SDKs initialize correctly.
- Test account creation and sign-in if Authentication is enabled.
- Write a test document to Firestore and verify it in the Firebase Console.
- Read data back and confirm the expected values.
- Test the application with no network connection where offline behavior is relevant.
- Verify that unauthorized reads and writes are rejected.
- Inspect Android Studio Logcat for useful diagnostic information.
18. Common Errors and Solutions
| Error or Symptom |
Possible Cause |
Solution |
| google-services.json not found |
Configuration file is missing or misplaced |
Place it in the correct app module directory |
| No matching client found |
Registered application ID does not match the app |
Verify the application ID and download the correct configuration file |
| Gradle sync fails |
Incompatible plugin versions or unresolved dependencies |
Check the Gradle, Android Gradle Plugin, and Firebase compatibility requirements |
| Firebase service is unavailable |
Wrong project, incorrect configuration, or service not enabled |
Verify the Firebase project and service setup |
| Authentication fails |
Provider is disabled or credentials are invalid |
Enable the provider and validate the sign-in flow |
| Firestore permission denied |
Security rules reject the operation |
Check authentication, ownership, and rule conditions |
| Data is not visible |
Wrong collection path or project |
Verify the target project, collection, and document IDs |
| Dependency conflict |
Inconsistent Firebase library versions |
Use the Firebase BoM and remove individual versions from managed Firebase dependencies |
| Works on one device only |
Device configuration or Google Play services requirements differ |
Check device compatibility, network access, and service requirements |
19. Security Best Practices
- Enable only the Firebase services required by the application.
- Use Firebase Authentication where user identity is needed.
- Write and test Firestore or Realtime Database security rules.
- Restrict access to user-specific data by UID or another verified authorization policy.
- Never embed server credentials, private API keys, or service account JSON files in the Android application.
- Remember that google-services.json contains configuration identifiers and is not a security boundary.
- Use Firebase App Check where appropriate to help protect supported backend resources from unauthorized clients.
- Validate incoming data and handle errors safely.
- Keep dependencies updated and review Firebase service usage and billing.
- Use the Firebase Local Emulator Suite when you need a controlled environment for testing supported services and security rules.
20. Practical Exercises
Exercise 1: Create and Connect a Firebase Project
Create a Firebase project, register an Android app, add google-services.json, configure the Gradle plugin, and build the application successfully.
Exercise 2: Implement User Authentication
Build a login and registration screen using Firebase Authentication. Validate email and password input and display clear success and error states.
Exercise 3: Store Student Details
Use Cloud Firestore to store student names, course names, and active status. Display saved documents in a RecyclerView or Jetpack Compose list.
Exercise 4: Apply Security Rules
Restrict user-specific documents so only the corresponding authenticated user can read and update them. Test both permitted and denied requests.
Mini Project: Student Course Management App
- Create an Android application with registration and login screens.
- Connect the application to Firebase Authentication.
- Store course and student information in Cloud Firestore.
- Display course records and allow authorized users to update them.
- Add loading indicators, validation, and error handling.
- Test security rules and verify records in the Firebase Console.
21. Interview Questions and Answers
Q1. What is Firebase?
Answer: Firebase is Google's application development platform that provides services such as authentication, cloud databases, messaging, analytics, and crash reporting.
Q2. What is a Firebase project?
Answer: It is the central project that groups registered applications, configuration, and Firebase services.
Q3. What is google-services.json?
Answer: It is an Android app configuration file downloaded from Firebase that contains identifiers and configuration values used by Firebase tooling and SDK setup.
Q4. What is the Google Services Gradle plugin?
Answer: It processes the Firebase configuration file during the Android build so the relevant Firebase configuration can be used by the application.
Q5. What is the Firebase Android BoM?
Answer: It is a Bill of Materials that coordinates compatible versions of Firebase Android libraries, reducing version-management problems.
Q6. What is Firebase Authentication?
Answer: It provides identity and sign-in functionality using supported authentication providers.
Q7. What is Cloud Firestore?
Answer: It is a cloud-hosted document database that organizes data into collections and documents and supports queries and realtime listeners.
Q8. Does connecting Firebase automatically secure database access?
Answer: No. Developers must configure and test security rules, authentication, authorization, and data validation.
Q9. Can one Android app use multiple Firebase services?
Answer: Yes. An application can use several services, such as Authentication, Firestore, Cloud Messaging, and Crashlytics, with their required dependencies and configuration.
Q10. How do you troubleshoot a Firebase connection?
Answer: Verify the registered application ID, configuration file location, Gradle plugin, SDK dependencies, Firebase project, service configuration, network access, and security rules.
22. Quick Revision Checklist
- Create a Firebase project in the Firebase Console.
- Register the Android application using its exact application ID.
- Download google-services.json into the app module.
- Configure the Google Services Gradle plugin.
- Add the required Firebase SDK dependencies using the BoM.
- Synchronize Gradle and build the application.
- Enable and test the Firebase services used by the application.
- Configure authentication and secure database access.
- Test real reads and writes and handle failures.
- Monitor usage, security, and service costs before release.
23. Conclusion
Connecting an Android project to Firebase enables developers to integrate managed backend capabilities into mobile applications. The process involves creating a Firebase project, registering the Android app, adding google-services.json, configuring Gradle, and including the appropriate Firebase SDK libraries.
Once connected, developers can implement features such as authentication, cloud data storage, notifications, analytics, and crash reporting. A successful integration also requires careful testing, appropriate error handling, secure database rules, and responsible management of service usage.
Additional Learning Resources
Explore Android App Development with JustAcademy
Continue learning Android development and build practical mobile application projects.
Explore the Android App Development Course
Register for a Course Demo
Visit JustAcademy Official Website