gpt4 book ai didi

java - Firebase 允许在时间戳内插入

转载 作者:行者123 更新时间:2023-12-02 03:42:41 25 4
gpt4 key购买 nike

我尝试允许在程序启动后约 10 秒的时间戳内插入数据,我有以下数据结构

  • 数据
    • 项目
    • 时间
      • 时间

启动程序后,我将当前时间戳保存在 time 中,如下所示

firebaseRef.child("time").setValue(ServerValue.TIMESTAMP, listener);
firebaseRef.child("time").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long timestamp = (Long) dataSnapshot.getValue();
System.out.println(timestamp);

HashMap<String, Object> map = new HashMap<>();
map.put("time", timestamp);
firebaseRef.child("time").setValue(map, listener);
}

@Override
public void onCancelled(FirebaseError error) {
}
});

我制定了以下安全规则

"items": {
".read": true,
".write": true,
".validate": "newData.parent().child('time').child('time').val() + 10000 >= now"
}

但它不起作用,我的许可被拒绝。我的规则有什么问题吗?

最佳答案

问题之一肯定是您正在初始化:

firebaseRef.child("time").setValue(ServerValue.TIMESTAMP, listener);

这会将 time 的值设置为 long。

{
"time": 1460776272703
}

但是然后:

HashMap<String, Object> map = new HashMap<>();
map.put("time", timestamp);
ref.child("time").setValue(map, listener);

您在 time 上调用 setValue(),然后传入带有 time 键的 map ,因此最终会编写 时间/时间

{
"time": {
"time": 1460776272703
}
}

即使这是故意的,这样改变数据结构似乎也是一个坏主意。例如,在模拟器中我很快遇到了如下错误消息:

Type Error: + only operates on numbers and strings.

因为它试图将 JSON 对象(上面第二个代码段中的 /time)计算为数值。

我的工作片段更简单:

    Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/36658910");
ref.child("time").setValue(ServerValue.TIMESTAMP, listener);
/*ref.child("time").addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
Long timestamp = (Long) dataSnapshot.getValue();
System.out.println(timestamp);
dataSnapshot.getRef().setValue(timestamp);
}
public void onCancelled(FirebaseError error) { }
});*/

我像这样运行它,以便测试播种位置,然后我进行另一次运行,禁用初始 setValue() 并启用监听器,以测试更新。

对应的安全规则:

"time": {
".write": true,
".validate": "(!data.exists() && newData.val() == now) || newData.child('time').val() + 100000 >= now"
}

您会注意到,我有单独的情况来写入初始值(必须使用 ServerValue.TIMESTAMP 来匹配 now)和更新(必须使用 ServerValue.TIMESTAMP 来完成)和更新(必须使用上次写入后 100 秒内)。

关于java - Firebase 允许在时间戳内插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com