To use Firebase in your Android app, you need to add/register your app with your Firebase project:
- Open the Firebase console and in the project overview page, click the Android icon or Add app.
- Enter your app’s package name in the Android package name field. Make sure to enter the package name that your app is actually using. The package name value is case-sensitive, and it cannot be changed for this Firebase Android app after it’s registered with your Firebase project.
- Enter other app information: App nickname and Debug signing certificate SHA-1.
- Click Register app.
Add the Firebase Android configuration file to your app:
Click Download google-services.json to obtain your Firebase Android config file (google-services.json
) and then move your config file into the module (app-level) directory of your app.
In your (project-level) Gradle file (build.gradle
), add rules to include the Google Services Gradle plugin:
buildscript {
repositories {
google() // Google's Maven repository
}
dependencies {
classpath 'com.google.gms:google-services:4.3.10' // Google Services plugin
}
}
allprojects {
repositories {
google() // Google's Maven repository
}
}
Declare the dependencies in app/build.gradle
file:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // Google Services plugin
dependencies {
implementation platform('com.google.firebase:firebase-bom:30.1.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-firestore-ktx'
}
Add Firebase using the Firebase Assistant
The Firebase Assistant registers your app with a Firebase project and adds the necessary Firebase files, plugins, and dependencies to your Android project — all from within Android Studio!
- Open your Android project in Android Studio
- Open the Firebase Assistant: Tools > Firebase.
- In the Assistant pane, choose a Firebase product to add to your app. Expand its section, then click the tutorial link (for example, Analytics > Log an Analytics event).
- Click Connect to Firebase to connect your Android project with Firebase.
- Click the button to add a desired Firebase product (for example, Add Analytics to your app).
- Sync your app to ensure that all dependencies have the necessary versions.
- In the Assistant pane, follow the remaining setup instructions for your selected Firebase product.
- Add as many other Firebase products as you’d like via the Firebase Assistant!
To get a reference to a database, you must pass the database URL to getInstance()
, or for Kotlin+KTX: database()
.
Depending on the location of the database, the database URL will be in one of the following forms:
https://DATABASE_NAME.firebaseio.com
(for databases in us-central1
)https://DATABASE_NAME.REGION.firebasedatabase.app
(for databases in all other locations)
Write to database:
// Write a message to the database
val database = Firebase.database
val myRef = database.getReference("message")
myRef.setValue("Hello, World!")
data class User(val username: String? = null, val email: String? = null) {
}
val database = Firebase.database
val databaseRef = database.getReference("UserData")
fun writeNewUser(userId: String, name: String, email: String) {
val user = User(name, email)
//to add new user:
myRef.child("users").child(userId).setValue(user)
// to update user name:
myRef.child("users").child(userId).child("username").setValue(name)
}
Read from database:
To make your app data update in realtime, you should add a ValueEventListener
to the reference you just created.
The onDataChange()
method in this class is triggered once when the listener is attached and again every time the data changes, including the children.
// Read from the database
private lateinit var databaseRef: DatabaseReference
databaseRef = Firebase.database.getReference("UserData")
databaseRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
val value = dataSnapshot.getValue<String>()
Log.d(TAG, "Value is: $value")
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
})
Read once using get():
databaseRef.child("users").child(userId).get().addOnSuccessListener {
Log.i("firebase", "Got value ${it.value}")
}.addOnFailureListener{
Log.e("firebase", "Error getting data", it)
}
Unnecessary use of get()
can increase use of bandwidth and lead to loss of performance, which can be prevented by using a realtime listener as shown above.
For data that only needs to be loaded once and isn’t expected to change frequently, to get the data from the local disk cache instead of checking for an updated value on the server you can use addListenerForSingleValueEvent
.
Both setValue()
and updateChildren()
take an optional completion listener that is called when the write has been successfully committed to the database. If the call was unsuccessful, the listener is passed an error object indicating why the failure occurred.
databaseRef.child("users").child(userId).setValue(user)
.addOnSuccessListener {
// Write was successful!
}
.addOnFailureListener {
// Write failed
}
The simplest way to delete data is to call removeValue()
on a reference to the location of that data.
You can also delete by specifying null
as the value for another write operation such as setValue()
or updateChildren()
. You can use this technique with updateChildren()
to delete multiple children in a single API call.
When using Firebase Realtime Database in your app along with ProGuard, you need to consider how your model objects will be serialized and deserialized after obfuscation.
If you use DataSnapshot.getValue(Class)
or DatabaseReference.setValue(Object)
to read and write data, you will need to add rules to the proguard-rules.pro file:
# Add this global rule
-keepattributes Signature
# This rule will properly ProGuard all the model classes in
# the package com.yourcompany.models.
# Modify this rule to fit the structure of your app.
-keepclassmembers class com.yourcompany.models.** {
*;
}
for detailed information check out the official Firebase documentation: https://firebase.google.com/docs/database/