1

I am a beginner and I am making a simple android game in which a user sign in into the app and play the game. After the game finishes I want to add the current score of the user with previous score and then store this total score in Firebase and then again retrieve the score next time when the user plays game.

I am not getting on how should I save the Total score for every different user who sign in.

this is my firebase json tree https://drive.google.com/file/d/1T7-x3TP1TaA8_ntwfoRNdb2oMGV_swl6/view?usp=sharing

 private void updateScore() {
  TotalScore =  new Firebase("https://bscitquiz.firebaseio.com/Users/" + username +"/highScore");
    TotalScore.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

                Integer totalscore = dataSnapshot.getValue(Integer.class);
                totalscore = totalscore + mScore;
               dataSnapshot.getRef().setValue(totalscore);
            HighScore.setText("" +totalscore);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

}
KickIssue
  • 11
  • 5

2 Answers2

1

You can save each user's score under its name at the database and just update it each time.

the android java code is written like this -

public static void updateScore(Integer score, String userId) {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.child("Users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override public void onDataChange(DataSnapshot dataSnapshot) {
            Integer previousScore =  dataSnapshot.getValue(Integer.class);
            if (previousScore != null){
                previousScore = previousScore + score;
                dataSnapshot.getRef().setValue(previousScore);
            }
        }
        @Override public void onCancelled(DatabaseError databaseError) {
            Log.e("frgrgr", "onCancelled", databaseError.toException());
        }
    });
}

This way you retrieve the old score, update it, and send back to the database.

Now at this way you have only the score value under each user.

You can use the user's name for the child ref of "Users" if its unique or just generate an Id for each user.

Edit after understanding your need for a callback -

callback in android?

For adding a callback there are a few steps,

  1. open a new java class with the following code -

    public interface FireBaseCallbacks {
    interface GetScoreCallback {
    public void onGetScoreComplete(Integer score)
        }
    }
    
  2. add the callback parameter to your updateScore method -

    private void updateScore(FireBaseCallbacks.GetDevicesCallback callback) {
        ...
    }
    
  3. call the callback parameter after you get the value -

    Integer totalscore = dataSnapshot.getValue(Integer.class);
    callback.onGetScoreComplete(totalscore)
    
  4. call the method somewhere in your activity (at the point that you want to update the score) with this as a parameter to tell the callback where to come back to (regarding the activity) -

      updateScore(this)
    
  5. now for the last step, implement the FireBaseCallbacks.GetScoreCallback to your activity and then you'll be forced to implement its onGetScoreComplete method. implement it and inside it you get the score as a parameter to do what ever you wish :)

Hope this will help, let me know otherwise.

Itay Feldman
  • 846
  • 10
  • 23
  • can i use "https://bscitquiz.firebaseio.com/Users/" + username + "/totalscore" this reference for the total score saved in firebase....i am taking the username of the user! – KickIssue Mar 20 '18 at 08:36
  • Of course, just add a child after the user name's child - ref.child("Users").child(userId).child(totalscore) – Itay Feldman Mar 20 '18 at 08:38
  • i just updated the question with my updatescore method! The score is not updating! can you tell me where am i going wrong – KickIssue Mar 20 '18 at 08:42
  • It wont update because you didn't add anything to it.. you retrieved it, and set value back without adding any score to the total score.. I would also use my way to get the ref than your way which can lead to mistakes. You can basically just copy my code, i adjusted it for your purpose just add the set text on the TextView – Itay Feldman Mar 20 '18 at 08:51
  • yes i know that, but still I have set the value of total score to 1 in my firebase but it still shows me 0 (which i used to make layout). its not retrieving the value from firebase. – KickIssue Mar 20 '18 at 08:58
  • Try debugging, there is a possibility that it gets to the setText line before it gets the data, it happened to me before. I solved it with a callback method. – Itay Feldman Mar 20 '18 at 09:09
  • I updated the answer with a callback explanation. @KickIssue – Itay Feldman Mar 20 '18 at 09:41
  • I implemented your first answer without callback one! Its updating the totalscore but going into an infinite loop as everytime the current score gets added to the previous score it agains call the valuelistener and the score keeps on getting incremented! i have updated my code in question please chekout. – KickIssue Mar 21 '18 at 10:41
  • Change the event listener to single event listener like in my code – Itay Feldman Mar 21 '18 at 11:36
  • Glad it helped :) – Itay Feldman Mar 24 '18 at 09:53
0

You can have a path for score under User (for Eg: User/userId/score) where you can update the score each time after completing the game. Below is the javascript code.

firebase.database().ref('User').child(userId).child('score').set(currentScore).then(result => {
    const user = snap.val()
    const userKey = snap.key
}).catch (function(err) {
    console.error(err)
})

Here currentScore is the value you want to update.

You can go through this link if you want it in android: https://firebase.google.com/docs/database/android/read-and-write

Chandrika
  • 194
  • 12