简体   繁体   中英

How can i retrieve values of Firebase Nodes with random auto generated IDs in Android Using Kotlin

I don't know how to go about retrieving data from the Firebase Realtime Database where the values have randomly generated IDs as seen below. 在此处输入图片说明

To be able to get all the keys and values that exist under the 21-6-21 node, you need to loop through the DatasnaShot object, as in the following lines of code:

val rootRef = FirebaseDatabase.getInstance().reference
val dateRef = rootRef.child("SigninData").child("CSC101").child("21-6-21")
val valueEventListener = object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.children) {
            val key = ds.getkey()
            val value = ds.getValue(String::class.java)
            Log.d("TAG", "$key/$value")
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
    }
}
dateRef.addListenerForSingleValueEvent(valueEventListener)

The result in the logcat will be:

-Mf8...ESM/oma@gmail.com...
-Mf8...7nb/oma@gmail.com...
-Mf8...XJv/oma@gmail.com...

Edit:

private fun getDataFrom(date: String) {
    val rootRef = FirebaseDatabase.getInstance().reference
    val dateRef = rootRef.child("SigninData").child("CSC101").child(date)
    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            for (ds in dataSnapshot.children) {
                val key = ds.getkey()
                val value = ds.getValue(String::class.java)
                Log.d("TAG", "$key/$value")
            }
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
        }
    }
    dateRef.addListenerForSingleValueEvent(valueEventListener)
}

Now you can call the above method either with:

getDataFrom("21-6-21")

Or:

getDataFrom("22-6-21")

If you need to get them both, then you should use a get() call, and pass both Task objects to the whenAllSuccess(Task...<?> tasks) .

I believe this will work out for you.

    fun getDataFromFirebaseDatabase() {
        // Your path 
        database.getReference("SigninData/CSC101/21-6-21")
            .get()
            .addOnCompleteListener {
                //this checks if there were any exceptions or Errors generated and will Log the error in your Logcat.
                if (it.exception != null) Log.e("FirebaseDatabase", "Error", it.exception)
                // this checks if your result was successful or not and also, 
                //if it has children or not, if both conditions are satisfied,
                //it will enter the for loop and print all the
                // values along with their keys in logcat.
                if (it.isSuccessful && it.result.hasChildren()) {
                    for (i in it.result.children) {
                        //i.key will give you required key
                        Log.d("FirebaseDatabase", "key is ${i.key}")
                        // i.value will give respective value
                        // import the values as given in database, for your case it would be String so.
                        val data = i.value as String
                        Log.d("FirebaseDatabase", "value is $data")
                    }
                }
            }
    }

Note - This will read all the values inside 21-6-21 child

Your Logcat should look something like this.

//if there is an error
E/FirebaseDatabase: Error <Some Error Code Here>

//if Run is Successful
//since there are 3 entries in CSC101 node all three will be printed one by one
//like the example given below

D/FirebaseDatabase: key is Mf80wSd9neOAqlPhESM
D/FirebaseDatabase: value is oma@gmail.com You signed in for CSC101

The above code uses get() function which means your app will only read the database only once. Instead of get() you can also use:

  1. addChildEventListener()
  2. addValueEventListener()
  3. addListenerForSingleValueEvent()

All are for different purposes. Here are the Firebase Docs regarding these: https://firebase.google.com/docs/database/android/read-and-write#read_data

the 3rd one is similar to the get function but 3rd one will read from the cache memory and should be used when you are not expecting your data to change frequently.

1st and 2nd will get the results from the database as soon as there are changes made in the database nodes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM