Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-increment a value in Firebase

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. being stored. That's fine, but when I re-run the project, id is set equal to 1 again.

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

UPDATED FAILED

I used the following to pass the Firebase reference and a string to the function 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) {
    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.

like image 884
nothingness Avatar asked Mar 07 '15 14:03

nothingness


People also ask

How do I increment field value in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.

Is it possible to set an Auto_increment field value manually?

The default value is Yes. If you want to manually assign a value to a field that has the AutoIncrement property set to Yes, you must be member of the SQL Server db_owner database permission set.

What is getKey in firebase?

getKey. public @Nullable String getKey() Returns. @Nullable String. The key name for the source location of this snapshot or null if this snapshot points to the database root.

What is uf8ff firebase?

The character \uf8ff used in the query is a very high code point in the Unicode range (it is a Private Usage Area [PUA] code). Because it is after most regular characters in Unicode, the query matches all values that start with queryText .


1 Answers

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.");
            }
        }
    });
}
like image 184
stkent Avatar answered Sep 20 '22 13:09

stkent