0

I have been trying since yesterday to add a value to my Firebase Database, I have tried several methods but I cannot do it.

When the user looks at a RewardedAD this call addCard which is supposed to add to the current user 1 card, and each time it adds a card to him without deleting the value.

this is my code for the RewardedAd (the Ad show correctly) :

@Override
public void onUserEarnedReward(@NonNull RewardItem reward) {
// User earned reward.
addCard();

And this is addCard :

private void addCard() {
    FirebaseUser user =  mAuth.getCurrentUser();

    mDatabase.child("users").child(user.getUid()).runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer carte = mutableData.getValue(Integer.class);
                mutableData.setValue(carte + 1);

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
    });
}

2 Answers2

0

Change mDatabase.child("users").child(user.getUid()) in your code with mDatabase.child("users").child(user.getUid()).child("carte") It will be created

MMG
  • 3,226
  • 5
  • 16
  • 43
0

I guess you are trying to create the filed of it doesn't exist through transaction

Maybe this is what your structure should look like:

users
|
|-----------UID
             |
             ---card : 1 //and you want to keep updating this

Try this:

private void addCard() {
    FirebaseUser user =  mAuth.getCurrentUser();

mDatabase.child("users").child(user.getUid()).child("card").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Integer card = mutableData.getValue(Integer.class);

         if(card == null){
          //if no card exist yet start with 1
          mutableData.setValue(1);  
          return Transaction.success(mutableData);

         }else{
         //there is card just increment it +1
         mutableData.setValue(card + 1);

         }


        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
});
}
Hasan Bou Taam
  • 4,017
  • 2
  • 12
  • 22
  • Hi, sorry I have solve my issue when creating the Field Carte in register ^^ and it's work but, now I try to delete number of Carte when user use NumberPicker in alertDialog, it works but I don't know why my app crash when I remove value of Carte, but it's works. – Victor Appercé Apr 28 '20 at 08:22
  • It must be some other problem, in your code and thus another question. But if the above code worked for you it must be the solution for your problem, anything else I guess you must ask a new question. – Hasan Bou Taam Apr 28 '20 at 13:04