Combine Firebase Realtime Database and Consumer Authentication into your Android App

This is a part of the Firebase educational sequence:

This text is the continuity of the former article, through which we realized easy methods to create a easy Firebase sign-in/authentication within the Android app.

So, this assumes you may have already arrange the Firebase console venture on your app. The review of the demo app looks as if this.

1. Allow Realtime Database in Firebase Challenge

At the left panel of your Firebase venture, click on Construct -> Realtime Database.

Click on Create Database.

In Database choices, let’s use the database location from the USA. Click on Subsequent.

In Safety regulations, let’s make a choice take a look at mode and click on Allow.

No matter what you select right here, we are going to alternate the protection later.

Congratulation! Now Firebase Realtime Database is enabled on your venture.

2. Trade Safety Regulations to Content material-owner handiest Get entry to

Move to Realtime Database -> Regulations, you spot one thing like this.

It approach everybody who installs your app can learn or write in your database earlier than the expiration date. This is typically for construction functions.

What we would like here’s handiest the authenticated person can handiest get entry to a definite trail of the database.

So, I’ll alternate the principles to the next.

{
  "regulations": {
    "customers": {
      "$uid": {
        ".learn": "auth !== null && auth.uid === $uid",
        ".write": "auth !== null && auth.uid === $uid"
      }
    }
  }
}

Those regulations imply handiest the authenticated person can get entry to (learn from and write to) the customers<uid> trail. uid is the original string ID this is assigned to the |Firebase person.

The legitimate report reference is right here.

3. Upload Firebase Database SDK in your App

construct.gradle/kts (app degree)

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

4. Write Consumer Knowledge to Database

The Firebase Realtime Database helps the Kotlin information magnificence serialization and deserialization. So as a substitute of working on each and every unmarried person information at once, you’ll be able to create UserData information magnificence underneath to carry them.

information magnificence UserData (
    val title:String?,
    val age: Int?,
    val favoriteFood:Checklist<String>?
) {
    
    
    constructor() : this(null, null, null)
}

The gotcha is you MUST create a no-argument conustructor(). Firebase database throws the exception while you attempt to learn the information from it. Rattling it, it tooks me someday to determine this out and it isn’t documented any place.

Write Knowledge to Database

After we signed in, we will retrieve the FirebaseUser from FirebaseAuth.getInstance().currentUser. From right here, we will get the FirebaseUser.uid.

To get the connection with /customers/<uid> trail within the database, we use Firebase.database.reference.kid("customers").kid(person.uid). A Firebase reference represents a selected location on your Database and can be utilized for studying or writing information to that Database location.

Then, we will name DatabaseReference.setValue() to put in writing the information into the database.

val person = FirebaseAuth.getInstance().currentUser
person?.run {
    val userIdReference = Firebase.database.reference
        .kid("customers").kid(person.uid)
    val userData = UserData(
        title = displayName,
        age = 7,
        favoriteFood = listOf("Apple", "Orange")
    )
    userIdReference.setValue(userData)
}

Ahead of you write the information, within the Firebase console Realtime Database information tab, it looks as if this, which does not comprise any information.

After you write information into it, it turns into like this.

5. Learn Consumer Knowledge from Database

Learn Knowledge from Database (One-time Learn)

The DatabaseReference.Get() returns Process<DataSnapshot> which lets you sign in a callback from the duty. To learn information, we sign in this callback process, Process.addOnSuccessListener().

val person = FirebaseAuth.getInstance().currentUser
person?.run {
    val userIdReference = Firebase.database.reference
        .kid("customers").kid(uid)

    userIdReference.get().addOnSuccessListener { dataSnapShot ->
        val userData = dataSnapShot.getValue<UserData?>()
        
    }
}

Learn Knowledge from Database (Steady Learn)

If you wish to incessantly studying the information as a substitute studying on-demand, you sign in this ValueEventListener with DatabaseReference.addValueEventListener(). Within the onDataChange() callback, you’ll be able to reveal the UserData to both Go with the flow or StateFlow.

val person = FirebaseAuth.getInstance().currentUser
val userIdReference = Firebase.database.reference
    .kid("customers").kid(person!!.uid)

userIdReference.addValueEventListener(object : ValueEventListener {
    override a laugh onDataChange(dataSnapshot: DataSnapshot) {
        val userData = dataSnapshot.getValue<UserData?>()
        
    }

    override a laugh onCancelled(error: DatabaseError) {
    }
})

Subsequent Steps

The Firebase Realtime database is straightforward to arrange (perhaps now not? As it took me some time, too). The disadvantage of the use of it isn’t totally loose, particularly after you end your quota. I can discover MangoDB subsequent…

Supply Code

GitHub Repository: Demo_FirebaseSignInRealtimeDB

Leave a Comment

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