Java – Android: Firebase digital increments

Android: Firebase digital increments… here is a solution to the problem.

Android: Firebase digital increments

I stick with using Firebase to increment a value in Java, but the problem is that it doesn’t update global variables. When I call EventListener at onStart, it successfully shows me the correct value of the variable (60). When I want to increase it by 10 – click the button – it shows as 0.

long value;

@Override
protected void onStart() {
    super.onStart();

final TextView mValue = (TextView) findViewById(R.id.some_textview);

mRef = new Firebase(some_correct_url);
    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            value = (long) dataSnapshot.getValue();
            mValue.setText(value+"");
        }

@Override
        public void onCancelled(FirebaseError firebaseError) {

}
    });
}

When a button is clicked, the following function is called

public void addTen(View view) {
    mRef = new Firebase(my_private_url);
    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            value =(long) dataSnapshot.getValue();
            value = value + 10;
        }
        @Override
        public void onCancelled(FirebaseError firebaseError) {
        }
    });

mRef.setValue(value);

}

So all in all, the first part retrieves the correct value of the variable, but the second part does not increase the correct value. Thanks in advance!

EDIT: By the way, I set the Firebase rule as follows:

{
"rules": {
".read": "true",
".write": "true"
}
}

This is for development time.

Solution

The Firebase listener fires asynchronously. Your call to mRef.setValue(value) is executed before the listener fires and updates value. Change your code like this:

public void addTen(View view) {
    mRef = new Firebase(my_private_url);
    mRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            value =(long) dataSnapshot.getValue();
            value = value + 10;
            dataSnapshot.getRef().setValue(value);
        }
        @Override
        public void onCancelled(FirebaseError firebaseError) {
        }
    });
}

Note that addListenerForSingleValueEvent() replaces addValueEventListener(). I don’t think you want to pile up listeners every time you call addten().

Related Problems and Solutions