Java 在 Firebase 中自动增加一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28915706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:01:31  来源:igfitidea点击:

Auto-increment a value in Firebase

javaandroidfirebasefirebase-realtime-databaseauto-increment

提问by nothingness

How do I auto increment a value stored in Firebase from an Android client?

如何从 Android 客户端自动递增 Firebase 中存储的值?

Currently: I declare int id = 1. When I increment, I see the values 2, 3 etc. being stored. That's fine, but when I re-run the project, idis set equal to 1 again.

目前:我声明int id = 1. 当我递增时,我看到值 2、3 等被存储。这很好,但是当我重新运行该项目时,id再次设置为等于 1。

I want it to behave like a static variable, so I can create an id which will go from 1 to infinity without resetting.

我希望它表现得像一个静态变量,所以我可以创建一个从 1 到无穷大而无需重置的 id。

UPDATED FAILED

更新失败

I used the following to pass the Firebase reference and a string to the function incrementCounter.

我使用以下代码将 Firebase 引用和一个字符串传递给函数 incrementCounter。

if(language_chosen.equalsIgnoreCase("english"))
 {
   Firebase publRef = f.child("Language").child("English").child("Message");
   Firebase newPublRef = publRef.push();
   writeMsgActivity demo = new writeMsgActivity();
   demo.incrementCounter(newPublRef,the_msg_enter);                                 
  }

Now I try to use the passed reference and string at public void incrementCounter(Firebase publref,String my_msg)in the oncomplete method but it gives me an error.

现在我尝试public void incrementCounter(Firebase publref,String my_msg)在 oncomplete 方法中使用传递的引用和字符串, 但它给了我一个错误。

   public void incrementCounter(Firebase publref,String my_msg) {
    publref.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                System.out.println("Firebase counter increment failed.");
            } else {
                System.out.println("Firebase counter increment succeeded.");

                Map<String, Object> publ = new HashMap<String, Object>();
                publ.put("pubMsg", my_msg);
                publ.put("id",currentData);
                publref.setValue(publ);
            }
        }
    });
}

UPDATED SOLVED

更新已解决

                final Firebase upvoteref = new Firebase("https://shareurday.firebaseio.com/Message/"+msg_id+"/upvotes"); 

            upvoteref.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(final MutableData currentData) {
                    if (currentData.getValue() == null) {
                        currentData.setValue(1);
                    } else {
                        currentData.setValue((Long) currentData.getValue() + 1);
                    }
                    return Transaction.success(currentData);
                }

                public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
                    if (firebaseError != null) {
                        System.out.println("Firebase counter increment failed.");
                    } else {
                        System.out.println("Firebase counter increment succeeded.");
                    }
                }
            });

The variable msg_id is the random generated id from push.

变量 msg_id 是从推送中随机生成的 id。

采纳答案by stkent

Here's an example method that increments a single counter. The key idea is that you are either creating the entry (setting it equal to 1) or mutatingthe existing entry. Using a transaction here ensures that if multiple clients attempt to increment the counter at the same time, all requests will eventually succeed. From the Firebase documentation (emphasis mine):

这是一个递增单个计数器的示例方法。关键思想是您要么创建条目(将其设置为等于 1)要么改变现有条目。在此处使用事务可确保如果多个客户端同时尝试增加计数器,则所有请求最终都会成功。从 Firebase 文档(强调我的):

Use our transactions feature when working with complex data that could be corrupted by concurrent updates

在处理可能被并发更新破坏的复杂数据时使用我们的事务功能

public void incrementCounter() {
    firebase.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        @Override
        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                Log.d("Firebase counter increment failed.");
            } else {
                Log.d("Firebase counter increment succeeded.");
            }
        }
    });
}

回答by AtulK

A new feature is added to firestore to autoincrement values. As simple as

向 firestore 添加了一项新功能以自动增加值。就这么简单

document("fitness_teams/Team_1").
  updateData(["step_counter" : FieldValue.increment(500)])

refer link: https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html

参考链接:https: //firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html

Used below code in my project.

在我的项目中使用以下代码。

var firestore = Firestore.instance;
firestore.collection('student').document('attendance').updateData({'total_attendace': FieldValue.increment(1)});