Insert integer if doesn't exist, increment if already exists in Firebase realtime database Android

user3787635 :

I am trying to generate a random integer between 1 & 5 and insert the integer in Firebase database when saveData() is called first time. After the first time, when saveData() is called the integer should be incremented(new generated integer should be added to previously inserted integer). Every time saveData() is called below code over writes the previously inserted integer instead of incrementing the integer.

protected fun saveData() {
    val randomInt = Random().nextInt((5-1) + 1)//generates int between 1 & 5
    val user = User(randomInt)

    val currentUser = mAuth?.currentUser
    val uid: String = currentUser!!.uid
    val ref = FirebaseDatabase.getInstance().getReference("users").child(uid)

    ref.setValue(user).addOnCompleteListener {
        Toast.makeText(this,"Successful" , Toast.LENGTH_SHORT).show()
    }
}

User.kt

class User(val randomInt: Int)

Structure which I am getting in firebase database after saveData() is called for lets say 3 times and lets say random integers generated each time are 2, 1 and 4:

    my-firebase-app-5c40
       |__-Lhi7dewd7878dew
               |__randomInt: 4 //2 is overwritten 1 and 1 is overwritten by 4 

Whereas I want it to be:

        my-firebase-app-5c40
       |__-Lhi7dewd7878dew
               |__randomInt: 7 //2 + 1 + 4

So, in a nutshell I want to increment the value of randomInt everytime saveData() is called instead of overwriting the previous inserted value which is happening with my current code.

Frank van Puffelen :

You're looking for a Firebase Database transaction, which is the only reliable way to update a property based on its existing value in a multi-user environment. Based on the example in the documentation, your code should look something like this:

val ref = FirebaseDatabase.getInstance().getReference("users").child(uid).child("randomInt")

ref.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Long value = mutableData.getValue(Long.class);
        if (p == null) {
            mutableData.setValue(1L);
            return Transaction.success(mutableData);
        }
        else {
            mutableData.setValue(value + 1);
        }

        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b,
                           DataSnapshot dataSnapshot) {
        Log.d(TAG, "transaction:onComplete:" + databaseError);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94275&siteId=1