函数 onDataChange() 从之前的片段 firebase android kotlin 调用

发布于 2025-01-12 20:35:20 字数 1946 浏览 1 评论 0原文

我遇到了一个相当奇怪的问题。在我的片段中,有一段代码用于通过 child().setValue() 将项目添加到数据库。在另一个片段中有用户授权,它检查用户是否存在,也是使用 onDataChange() 函数实现的。

检查用户功能[AuthFragment]:

private fun checkUserExist() {
    val ref = FirebaseDatabase.getInstance().getReference("Users")

    ref.child(auth.uid!!)
        .addValueEventListener(object: ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            if (snapshot.exists()) {
                // User exist
                findNavController().navigate(R.id.action_authSecondStepFragment_to_authCompletedFragment)
            } else {
                // User not exist
                saveUser()
            }
        }

        override fun onCancelled(error: DatabaseError) {
            throw error.toException()
        }
    })
}

向数据库添加项目功能[AddingToDatabaseFragment]:

private fun addToFavorite() {
    val hashMap = HashMap<String, Any>()

    with(args) {
        hashMap["id"] = getPlaceId()
        hashMap["name"] = currentPlace.name
        hashMap["location"] = currentPlace.description
        hashMap["image"] = currentPlace.image
        hashMap["description"] = currentPlace.description
    }

    val ref = FirebaseDatabase.getInstance().getReference("Users")
    ref.child(getProfileUid()!!)
        .child("Favorites")
        .child(getPlaceId())
        .setValue(hashMap)
        .addOnSuccessListener {
            Toast.makeText(requireContext(), "Succesfully added!", Toast.LENGTH_SHORT).show()
        }
        .addOnFailureListener {
            Toast.makeText(requireContext(), "Error!", Toast.LENGTH_SHORT).show()
        }
}

实际上,问题在于通过onDataChange() 函数,我到达另一个片段,其中我已经可以向数据库添加一些项目,并且在添加(分别更改数据库)时,来自的 onDataChange() 函数PREVIOUS 授权片段,在我的例子中,findNavController() 是从我不在的片段中调用的,这会导致应用程序崩溃。我该如何解决这个问题?

I ran into a rather strange problem. In my fragment there is a code for adding an item to the database through the child().setValue(). In another fragment there is user authorization, where it checks if the user exists, it is also implemented using the onDataChange() function.

Check user function [AuthFragment]:

private fun checkUserExist() {
    val ref = FirebaseDatabase.getInstance().getReference("Users")

    ref.child(auth.uid!!)
        .addValueEventListener(object: ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            if (snapshot.exists()) {
                // User exist
                findNavController().navigate(R.id.action_authSecondStepFragment_to_authCompletedFragment)
            } else {
                // User not exist
                saveUser()
            }
        }

        override fun onCancelled(error: DatabaseError) {
            throw error.toException()
        }
    })
}

Adding item to database function [AddingToDatabaseFragment]:

private fun addToFavorite() {
    val hashMap = HashMap<String, Any>()

    with(args) {
        hashMap["id"] = getPlaceId()
        hashMap["name"] = currentPlace.name
        hashMap["location"] = currentPlace.description
        hashMap["image"] = currentPlace.image
        hashMap["description"] = currentPlace.description
    }

    val ref = FirebaseDatabase.getInstance().getReference("Users")
    ref.child(getProfileUid()!!)
        .child("Favorites")
        .child(getPlaceId())
        .setValue(hashMap)
        .addOnSuccessListener {
            Toast.makeText(requireContext(), "Succesfully added!", Toast.LENGTH_SHORT).show()
        }
        .addOnFailureListener {
            Toast.makeText(requireContext(), "Error!", Toast.LENGTH_SHORT).show()
        }
}

Actually, the problem is that when successfully authorizing through the onDataChange() function, I get to another fragment, where I can already add some item to the database, and when adding (respectively, changing the database), the onDataChange() function from of the PREVIOUS authorization fragment, in my case findNavController() is called from a fragment that I am not even in, which causes the application to crash. How can I fix this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ㄟ。诗瑗 2025-01-19 20:35:20

由于您使用了addValueEventListener,因此您正在注册一个永久侦听器。停用该侦听器的唯一方法是分离它,通常是当它超出范围时。

我通常尝试将听众的附加和分离放在活动的相反生命周期事件中。因此,如果我在 onStart 中附加,我将在 onStop 中分离,对于 onUnpause/onResume 也是如此。

对于片段,您应该遵循相同的逻辑,因此 onAttach -> onDetach,或onStart -> onStoponPause -> onResume

Since you use addValueEventListener, you are registering a permanent listener. The only way to deactivate that listener is by detaching it, typically when it goes out of scope.

I usually try to put my attaching and detaching of listeners in the opposite life-cycle events of my activities. So if I attach in onStart I'll detach in onStop, and same for onUnpause/onResume.

For fragments you should follow the same logic, so onAttach -> onDetach, or onStart -> onStop, or onPause -> onResume.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文