简体   繁体   中英

how to get some child list from Firebase android kotlin?

Firebase 实时数据库

How i can read just color item in the image with out all data sub child?

I try this

val database = FirebaseDatabase.getInstance()
val personalDataReference = database.getReference("user personal data")
val messageList = ArrayList<String>()
personalDataReference.addValueEventListener(object : ValueEventListener{
    override fun onDataChange(dataSnapshot: DataSnapshot){
        messageList.add(dataSnapshot.value.toString())
    }
    override fun onCancelled(error: DatabaseError) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException())
    }
})

but it get all the data

Consider using the Firebase Kotlin SDK by GitLive.

This library is also multi-platform, so the same code can be used on both Android and on iOS via Kotlin Multiplatform Mobile .

The code to read the keys from Firebase realtime database would look like this:

val keys = db.reference("/path/to/user personal data")
  .valueEvents
  .first()
  .children
  .mapNotNull { it.key }

Note here that valueEvents is a Kotlin Flow of DataSnapshot , therefore you can do more than simply taking the first snapshot and mapping it to a list as shown above. See the Flow documentation.

The things you've marked yellow are known as keys in Firebase terms.

To get a list of only the keys, you can do:

personalDataReference.addValueEventListener(object : ValueEventListener{
    override fun onDataChange(dataSnapshot: DataSnapshot){
      for (childSnapshot in dataSnapshot.children) {
        messageList.add(childSnapshot.key)
      }
    }

Note that this will still read all JSON from the database, but the list will only contain the keys.

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