That is a part of the Firebase tutorial sequence:
This text is the continuity of the earlier article, by which we discovered the way to create a easy Firebase sign-in/authentication within the Android app.
So, this assumes you have got already arrange the Firebase console undertaking to your app. The overview of the demo app appears like this.
1. Allow Realtime Database in Firebase Venture
On the left panel of your Firebase undertaking, click on Construct -> Realtime Database.
Click on Create Database.
In Database choices, let’s use the database location from the US. Click on Subsequent.
In Safety guidelines, let’s select check mode and click on Allow.
It does not matter what you select right here, we will change the safety later.
Congratulation! Now Firebase Realtime Database is enabled in your undertaking.
2. Change Safety Guidelines to Content material-owner solely Entry
Go to Realtime Database -> Guidelines, you see one thing like this.
It means everybody who installs your app can learn or write to your database earlier than the expiration date. That’s normally for improvement functions.
What we wish right here is simply the authenticated person can solely entry a sure path of the database.
So, I will change the principles to the next.
{
"guidelines": {
"customers": {
"$uid": {
".learn": "auth !== null && auth.uid === $uid",
".write": "auth !== null && auth.uid === $uid"
}
}
}
}
These guidelines imply solely the authenticated person can entry (learn from and write to) the customers<uid> path. uid is the distinctive string ID that’s assigned to the |Firebase person.
The official doc reference is right here.
3. Add Firebase Database SDK to your App
construct.gradle/kts (app degree)
dependencies {
implementation("com.google.firebase:firebase-database-ktx:20.1.0")
}
4. Write Consumer Information to Database
The Firebase Realtime Database helps the Kotlin information class serialization and deserialization. So as an alternative of working on each single person information instantly, you’ll be able to create UserData
information class under to carry them.
information class UserData (
val identify:String?,
val age: Int?,
val favoriteFood:Record<String>?
) {
constructor() : this(null, null, null)
}
The gotcha is you MUST create a no-argument
conustructor()
. Firebase database throws the exception if you attempt to learn the info from it. Rattling it, it tooks me someday to determine this out and it isn’t documented anyplace.
Write Information to Database
As soon as we signed in, we will retrieve the FirebaseUser
from FirebaseAuth.getInstance().currentUser
. From right here, we will get the FirebaseUser.uid
.
To get the reference to /customers/<uid> path within the database, we use Firebase.database.reference.youngster("customers").youngster(person.uid).
A Firebase reference represents a specific location in your Database and can be utilized for studying or writing information to that Database location.
Then, we will name DatabaseReference.setValue()
to write down the info into the database.
val person = FirebaseAuth.getInstance().currentUser
person?.run {
val userIdReference = Firebase.database.reference
.youngster("customers").youngster(person.uid)
val userData = UserData(
identify = displayName,
age = 7,
favoriteFood = listOf("Apple", "Orange")
)
userIdReference.setValue(userData)
}
Earlier than you write the info, within the Firebase console Realtime Database information tab, it appears like this, which does not comprise any information.
After you write information into it, it turns into like this.
5. Learn Consumer Information from Database
Learn Information from Database (One-time Learn)
The DatabaseReference.Get()
returns Job<DataSnapshot>
which lets you register a callback from the duty. To learn information, we register this callback process, Job.addOnSuccessListener()
.
val person = FirebaseAuth.getInstance().currentUser
person?.run {
val userIdReference = Firebase.database.reference
.youngster("customers").youngster(uid)
userIdReference.get().addOnSuccessListener { dataSnapShot ->
val userData = dataSnapShot.getValue<UserData?>()
}
}
Learn Information from Database (Steady Learn)
If you wish to repeatedly studying the info as an alternative studying on-demand, you register this ValueEventListener
with DatabaseReference.addValueEventListener()
. Within the onDataChange()
callback, you’ll be able to expose the UserData
to both Stream
or StateFlow
.
val person = FirebaseAuth.getInstance().currentUser
val userIdReference = Firebase.database.reference
.youngster("customers").youngster(person!!.uid)
userIdReference.addValueEventListener(object : ValueEventListener {
override enjoyable onDataChange(dataSnapshot: DataSnapshot) {
val userData = dataSnapshot.getValue<UserData?>()
}
override enjoyable onCancelled(error: DatabaseError) {
}
})
Subsequent Steps
The Firebase Realtime database is straightforward to arrange (possibly not? As a result of it took me some time, too). The disadvantage of utilizing it isn’t utterly free, particularly after you end your quota. I’ll discover MangoDB subsequent…
Supply Code
GitHub Repository: Demo_FirebaseSignInRealtimeDB