Auto-increment a value in Firebase

前端 未结 2 576
一整个雨季
一整个雨季 2020-12-05 05:43

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

Currently: I declare int id = 1. When I increment, I see the values 2, 3 etc.

相关标签:
2条回答
  • 2020-12-05 06:09

    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 mutating the 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):

    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.");
                }
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-05 06:22

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

    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

    Used below code in my project.

    var firestore = Firestore.instance;
    firestore.collection('student').document('attendance').updateData({'total_attendace': FieldValue.increment(1)});
    
    0 讨论(0)
提交回复
热议问题