android - 如何同步firebase数据?

标签 android firebase

enter image description here

我正在使用 firebase 来存储我的数据。这就是我的 firebase 数据库的样子。 在我的代码中,我试图在按钮单击事件上生成一个新的唯一appointment-id。如果当前的 appointment-id 是 88,那么当用户按下应用程序上的按钮时,它应该变成 89,并且这个 appointment-id 被分配给他作为他唯一的 约会 ID。我面临的问题是,当两个或多个用户同时按下应用程序上的按钮时,相同的 appointment-id 会分配给他们两个。

我希望同步我的appointment-id,即一次只有一个用户可以访问它。这可能吗?我怎样才能实现它?谢谢。

最佳答案

Firebase 的事务可以帮助您进行增量计数器

Firebase apptRef = new Firebase("<my-firebase-app>");
apptRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData currentData) {
        if(currentData.getValue() == null) {
            currentData.setValue(1);
        } else {
            currentData.setValue((Long) currentData.getValue() + 1);
        }
        return Transaction.success(currentData); //we can also abort by calling Transaction.abort()
    }
    @Override
    public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
        //This method will be called once with the results of the transaction.
    }
});

阅读Firebase docs了解更多信息。

关于android - 如何同步firebase数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33969825/

相关文章:

android - Recyclerview数据在刷卡刷新多次后重复

android - 从另一个类调用 Activity - Android

ios - 在 Swift 中传递变量

java - Android 多文件上传到服务器

安卓标记 : onTouch should call View#performClick when a click is detected

android - minSdkVersion 21 使应用程序崩溃。 20及以下工作正常

Firebase 查询 : exclude data where a specific field is null

android - 如何在没有网站的情况下实现 Android Firebase 动态链接?

android - 实现带有微调器和复选框的自定义 ListView

java - 在 sqlite 中存储包含对象列表的对象