如何从Firebase数据库中检索数据并将其存储在ListArray <class>中? - 科特林

时间:2017-10-07 21:20:01

标签: firebase firebase-realtime-database kotlin

我在从Firebase DB中检索数据时遇到一些问题... 这是我的简单代码

class Match (val teamOne: String, val teamTwo: String, val betType: String)


private var database = FirebaseDatabase.getInstance()
private var myRef = database.getReference()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    myRef.child("matches").addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot?) {
            val matches = snapshot!!.children
            matches.forEach(){
                println(it.value.toString())
            }
        }
        override fun onCancelled(p0: DatabaseError?) {
        }
    })
}

这是我从DB获得的:

I / System.out:{bet = GG,team1 =尤文图斯,team2 =皇家马德里}

I / System.out:{bet =超过2.5,team1 = Napoli,team2 = Roma}

I / System.out:{bet = 2,team1 = Inter,team2 = Milan}

I / System.out:{bet = X,team1 = Atalanta,team2 = Lazio}

I / System.out:{bet = X,team1 = Crotone,team2 = Spezia}

我的问题是:如何立即创建ListArray<Match>

感谢大家!!!

1 个答案:

答案 0 :(得分:0)

如果您仍然想知道并且不想使用其他数据库,我可以通过两种方式实现此目的:

val mapper = object : GenericTypeIndicator<HashMap<String, Match>>() {}
val list = arrayListOf<Match>()
val map = snapshot.getValue(mapper)
map?.forEach {
    list.add(it.value)
}

或者:

val list = MutableList<Match> = mutableListOf()
snapshot.children.mapNotNullTo(list) {
    it.getValue<Match>(Match::class.java)
}

免责声明: Match类可能必须是data class