0

I have a button for logged in users. When a logged in user clicks the button, I want to increase a specific value for this specific user. Now I am using the below code, but it creates a child in a Firebase database and increases data. I want that it should increase a specific (logged in) user child ("points") data.

myRef.child("points").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(final MutableData currentData) {
        if (currentData.getValue() == null) {
            currentData.setValue("0");
        } else {
            String stringValue = (String) currentData.getValue();
            int intValue = Integer.parseInt(stringValue);
            int increasedIntValue = intValue + 1;
            currentData.setValue(String.valueOf(increasedIntValue));
        }
        return Transaction.success(currentData);
    }

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

The database:

Image of database

What can I do now?

André Kool
  • 4,880
  • 12
  • 34
  • 44
  • Check **[this](https://stackoverflow.com/questions/48307610/how-to-save-users-score-in-firebase-and-retrieve-it-in-real-time-in-android-stud)**. – Alex Mamo May 21 '18 at 06:39

1 Answers1

0
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.addListenerForSingleValueEvent(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild("points")) {
              if (dataSnapshot.getValue() == null) {
              dataSnapshot.setValue("0");
             } else {
            String stringValue = (String) dataSnapshot.getValue();
            int intValue = Integer.parseInt(stringValue);
            int increasedIntValue = intValue + 1;
            dataSnapshot.setValue(String.valueOf(increasedIntValue));
}}

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

addListenerForSingleValueEvent :This listener helps you to detect the change in the data at a particular path (including the children at that particular path). This listener listens exactly once and provides you the data as per the change until this event was triggered.