Reading data in android Kotlin from Firebase Realtime database, is a very important task while creating IoT system with the help of Firebase. Today, we will discuss the simple reading methods from Firebase Realtime database in Kotlin. We normally need to wait for data change in some variable on the database. Here are some ways of reading data in Kotlin. There is official guide from the Firebase itself about reading data.
Get Firebase Realtime Database Reference
First of all, we need to make sure to get the reference for our realtime database. In kotling we can use the lateinit var
for creating the reference initialization. Here is how you can do that.
private lateinit var database: DatabaseReference
Code language: Kotlin (kotlin)
You can initialize this variable inside onCreate
function like follows.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
database = Firebase.database.reference
}
Code language: Kotlin (kotlin)
Similarly, if you want to make reference for some specific variable, you can simply get that reference like follows.
val database = Firebase.database
val myRef = database.getReference("cmd")
Code language: Kotlin (kotlin)
Modify Security Rules
Next you need to modify the security rules for your Firebase Realtime database. If you make it public it would be temporary for 28 days. You can declare them public to test your codes. This way you do not have to make the authentication setup to just check your firebase realtime database CRUD operations. Here is the way to make your security rules full public.
{
"rules": {
".read": true,
".write": true
}
}
Code language: JSON / JSON with Comments (json)
This will show you Critical Warning like this Your security rules are defined as public, so anyone can steal, modify, or delete data in your database
.
Otherwise, if you want to make sure that the access is only available if the user is logged in properly before reading the realtime database, you can modify the rules like follows.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Code language: JSON / JSON with Comments (json)
You can learn more about Firebase Realtime Database Security Rules and how to use the auth
variable in the official documentation or this Stack Overflow answer.
A quick answer from Bing Ai tells about security rules something like,
The expression firebase auth is not null is a boolean expression that checks whether the auth object in Firebase is not null. This expression is commonly used in security rules to restrict access to authenticated users only.
When auth is not null, it means that the user is authenticated and has a valid ID token 12. The ID token is a JSON Web Token (JWT) that contains claims about the identity of the authenticated user 3. The ID token is signed with a private key and can be verified using the public key 3. Therefore, it is difficult to fake an ID token without possessing the private key 12.
However, it is important to note that
Bing copilot AIauth !== null
does not guarantee that the user has access to the data 1. The security rules must be defined appropriately to ensure that the user has the required permissions to read or write the data 12.
Reading Data with addValueEventListener
You can now simply wait for event change with the help of addValueEventListener
available inside the database reference variable. You can read the complete variables inside these reference variables with the following code.
myRef.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val cmdObject = snapshot.value as? Map<*, *>
if (cmdObject != null) {
// Now you can access the fields of your object
val command = cmdObject["Command"]
val h1 = cmdObject["H1"]
val h2 = cmdObject["H2"]
val m1 = cmdObject["M1"]
val m2 = cmdObject["M2"]
if (h1 != null) {
editTextH1.setText(h1.toString())
}
if (m1 != null) {
editTextM1.setText(m1.toString())
}
if (h2 != null) {
editTextH2.setText(h2.toString())
}
if (m2 != null) {
editTextM2.setText(m2.toString())
}
// Display the values using Toast
val message = "Command: $command, H1: $h1, H2: $h2, M1: $m1, M2: $m2"
showToast(message)
} else {
// Handle the case when the data is not in the expected format
showToast("Data format is not as expected")
}
} else {
// Handle the case when the data does not exist
showToast("Data does not exist")
}
}
override fun onCancelled(error: DatabaseError) {
showToast("Error: ${error.message}")
}
})
Code language: Kotlin (kotlin)