Skip to content Skip to sidebar Skip to footer

How To Read Data From Firebase Based On A Key Value In Kotlin

I want to retrieve data from firebase using Kotlin and android studio. This is my data class which is used to upload data into firebase: class Data(var id : String, var

Solution 1:

Now I want to retrieve data from firebase where the value of phone number matches the given string.

To solve this, you need to use a query, like in the following lines of code:

val rootRef = FirebaseDatabase.getInstance().reference
val ordersRef = rootRef.child("orders").orderByChild("phonenumber").equalTo(givenString)
val valueEventListener = object : ValueEventListener {
    overridefunonDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val username = ds.child("username").getValue(String::class.java)
            Log.d(TAG, username)
        }
    }

    overridefunonCancelled(databaseError: DatabaseError) {
        Log.d(TAG, databaseError.getMessage()) //Don't ignore errors!
    }
}
ordersRef.addListenerForSingleValueEvent(valueEventListener)

The result in your logcat, will be the user name that exist in the orders where the phone number is equal to a given string.

Post a Comment for "How To Read Data From Firebase Based On A Key Value In Kotlin"