从Firebase实时数据库复制数据

时间:2019-08-21 13:21:52

标签: android firebase firebase-realtime-database kotlin

有一种方法可以将数据从Firebase实时数据库添加到我的列表中:

--------------------------------
  ID  |   ORG  | DES | Type | B|
--------------------------------
 101  |  ABC   | KIL | A    | 1|
________________________________
 101  |  ABC   | KIL | B    | 5|
________________________________
 102  |  XYZ   | LOU | A    | 2|
________________________________
 102  |  XYZ   | LOU | B    | 6|
________________________________
 103  |  MNO   | HYT | A    | 3|
________________________________
 103  |  MNO   | HYT | B    | 7|
________________________________
 104  |  PQR   | HYT | A    | 4|
________________________________
 104  |  PQR   | HYT | B    | 8|
________________________________

但是有时候当我从一个片段跳到另一个片段时,我会有重复的数据列表。

问:我需要在某个地方private fun getTargetsFromDb() { val uid = firebaseUser!!.uid val targetsRef = databaseReference?.child("targets")?.child("users")?.child(uid)?.child("targets") val valueEventListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (targetSnapshot in dataSnapshot.children) { val target = targetSnapshot.getValue(Target::class.java) target?.let { targetList.add(it) } } recyclerView?.adapter = adapter } override fun onCancelled(databaseError: DatabaseError) { Log.d("some", "Error trying to get targets for ${databaseError.message}") } } targetsRef?.addListenerForSingleValueEvent(valueEventListener) } 收集remove的数据吗?

1 个答案:

答案 0 :(得分:3)

这可以帮助您清除旧数据并将新数据存储在列表中。

private fun getTargetsFromDb() {
        val uid = firebaseUser!!.uid
        val targetsRef = databaseReference?.child("targets")?.child("users")?.child(uid)?.child("targets")
        val valueEventListener = object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                targetList.clear()
                for (targetSnapshot in dataSnapshot.children) {
                    val target = targetSnapshot.getValue(Target::class.java)
                    target?.let { targetList.add(it) }
                }
                recyclerView?.adapter = adapter
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("some", "Error trying to get targets for ${databaseError.message}")
            }
        }
        targetsRef?.addListenerForSingleValueEvent(valueEventListener)
    }

以上代码将检查响应是否成功,然后将清除列表并存储值,或者将不清除列表而只给您例外。