为用户创建独特的笔记

时间:2019-03-26 11:42:13

标签: android firebase firebase-realtime-database kotlin

在应用程序Firebase身份验证中实现。以及添加和删除记录的功能。但是当我使用另一个帐户时,各地的记录都是相同的。

问:如何为每个授权用户创建自己的记录?

现在有这样的东西:

enter image description here

根据我的评论,我需要在结构中添加另一个字段:“用户”。最终得到类型target-list - > users - > targets

但是例如在我的主要活动中,我选择如下: databaseReference = FirebaseDatabase.getInstance().getReference("targets")

我如何理解这里必须更改结构?

UPD : 我尝试下一个:

private fun updateListData() {
    val uid = FirebaseAuth.getInstance().currentUser?.uid ?: ""
    databaseReference = FirebaseDatabase.getInstance().getReference("targets").child(uid)
    getTargetsFromDb()
}

和getTargetsFromDb()中:

private fun getTargetsFromDb() {
    databaseReference?.addValueEventListener(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}")
        }
    })
}

并获得下一个结构:

enter image description here

1 个答案:

答案 0 :(得分:0)

根据您的评论和消息,您想要分别为每个用户创建目标。使用您的实际结构,您可以分别拥有用户和目标。为了解决这个问题,我建议您使用另一个如下所示的数据库结构:

Firebase-root
  |
  --- targets
       |
       --- uid
            |
            --- pushedId
            |    |
            |    --- description: "some description"
            |    |
            |    --- name: "Vadim"
            |
            --- pushedId
                 |
                 --- description: "another description"
                 |
                 --- name: "Morozov"

要获取与特定用户对应的所有目标,只需使用以下查询:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().getReference()
val uidRef = rootRef.child("targets").child(uid)
uidRef.addListenerForSingleValueEvent(/* ... */);

另一种数据库结构可能是:

Firebase-root
  |
  --- targets
        |
        --- pushedId
        |    |
        |    --- description: "some description"
        |    |
        |    --- name: "Vadim"
        |    |
        |    --- uid: "VDMQ ... 0nw1"
        |
        --- pushedId
             |
             --- description: "another description"
             |
             --- name: "Svetlana"
             |
             --- uid: "eluk ... PJu1"

如您所见,它的级别比以前的结构小。现在,要获取与特定用户对应的所有目标,请使用以下查询:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().getReference()
val targetsRef = rootRef.child("targets").orderByChild("uid").equalTo(uid)
targetsRef.addListenerForSingleValueEvent(/* ... */);

因此,由您决定哪个更适合您。