Firebase实时数据库读取不存在的数据 [英] firebase realtime database reads data that doesnt exist

查看:76
本文介绍了Firebase实时数据库读取不存在的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们遇到了可能是firebase数据库中的主要错误,请参见下面的代码.下面的代码尝试为子级"EXAMPLE"设置值.没有读取或写入权限.写入操作不会向数据库写入任何内容,并且会引发错误"/EXAMPLE/VALUE处的setValue失败:DatabaseError:权限被拒绝"在日志中,这是一件好事.

但是,随后出现的代码的主要问题是在尝试读取子代"EXAMPLE"的值后,该代码实际上进入ondatachange方法,并以"ONE"的形式读取该值.而不是进入onCancelled方法以引发许可权错误,数据甚至不存在于数据库中,并且对于子"EXAMPLE"节点没有读或写许可权.那么fireabase怎么能声称读取了一个不存在的值.

  myReftwo.child("EXAMPLE").child("VALUE").setValue("ONE");myReftwo.child(示例").child("VALUE").addListenerForSingleValueEvent(new ValueEventListener(){@Override公共无效onDataChange(DataSnapshot dataSnapshot){Log.d("print",dataSnapshot.getValue().toString());}@Override公共无效的onCancelled(DatabaseError databaseError){Log.d("print",databaseError.getMessage());}}); 

解决方案

在您共享的代码段中,由于服务器拒绝,侦听器很可能在更新本地缓存之前从本地缓存获取值.

添加侦听器时,Firebase会尝试为您提供期望节点立即拥有的值.由于调用了 addListenerForSingleValueEvent ,因此它们立即停止监听该值.因此,您最终只能从本地缓存中看到过时的值,而从服务器中看不到实际值(或缺少实际值).

因此,您不应该在应用程序中同时使用磁盘持久性和 addListenerForSingleValueEvent .在同一情况下使用 addValueEventListener 会导致两次调用 onDataChange :第一个调用来自本地缓存的值,第二个调用来自服务器的正确快照

有关这些功能如何工作以及为什么它们不会导致您想要的行为的更详细的答案,请参见: 解决方案

In the snippet as you share it, most likely the listener is getting the value from the local cache before that cache has been updated because of the rejection from the server.

When you add a listener, Firebase tries to give you the value it expects the node to have immediately. And since you call addListenerForSingleValueEvent, it them immediately stops listening for the value. So you end up seeing only stale value from the local cache, and never see the actual value (or lack thereof) from the server.

For this reason you should not use both disk persistence and addListenerForSingleValueEvent in your app. Using addValueEventListener in the same scenario would lead to two calls to onDataChange: the first one with the value from the local cache, and the second one with the correct snapshot from the server.

For a longer answer on how these work, and why they don't result in the behavior you'd like, see: Firebase Offline Capabilities and addListenerForSingleValueEvent

这篇关于Firebase实时数据库读取不存在的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆