首页 > 解决方案 > Retrieving data from Firebase (Realtime Database) into a list (Kotlin)

问题描述

The RealtimeDatabase structure in Firebase

I want to go over the entire users in "mifkada" and to add them into a list as a BlogPost object:

class BlogPost (
  var namerv: String,
  var gafrv: String,
  var placerv: String,
  var phonerv: String,
  var notesrv: String
) {
  constructor() : this("", "", "", "", "") {}
}

I tried to do it with a for loop but it doesn't work the way I wrote it

class DataSource{

        companion object{

            fun createDataSet(): ArrayList<BlogPost>{


                var databaseMifkada = FirebaseDatabase.getInstance().getReference("mifkada")

                val list = ArrayList<BlogPost>()

                val postListener = object : ValueEventListener {
                    override fun onDataChange(dataSnapshot: DataSnapshot) {
                        if(dataSnapshot!!.exists()){
                            list.clear()
                            for (e in dataSnapshot.children){
                                val post = e.getValue(BlogPost::class.java)
                                list.add(post!!)
                            }
                        }
                    }

                    override fun onCancelled(databaseError: DatabaseError) {
                        // Getting Post failed, log a message
                        Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
                    }
                }

                databaseMifkada.addValueEventListener(postListener)

                return list
            }
      }
}

标签: listkotlinfirebase-realtime-databasesnapshotread-data

解决方案


The values of your constructor does not match the names of your database values

class BlogPost (
  var namerv: String,
  var gafrv: String,
  var placerv: String,
  var phonerv: String,
  var notesrv: String
) {
  constructor() : this("", "", "", "", "") {}
}

Should be

class BlogPost (
  var name: String,
  var gaf: String,
  var place: String,
  var phone: String,
  var notes: String
) {
  constructor() : this("", "", "", "", "") {}
}

You need to have the same name because when you do

val post = e.getValue(BlogPost::class.java)

it will look for those field names under the reference, and if it can't be reached, you can't get those values


推荐阅读