How to save users score in firebase and retrieve it in real-time in Android studio

前端 未结 3 438
日久生厌
日久生厌 2020-11-22 10:12

I am creating an app in which points increases on button click and those points should be saved to firebase. I managed to save those data to firebase. But when I destroy my

相关标签:
3条回答
  • 2020-11-22 10:29

    Edit: 29th, June 2020

    Now it's also possible to solve this problem without the use of a transaction. We can simply increment a value using:

    rootRef.child("score").setValue(ServerValue.increment(1));
    

    And for decremenet, the following line of code is required:

    rootRef.child("score").setValue(ServerValue.increment(-1));
    

    This is how you set a value in your Firebase database:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    rootRef.child("score").setValue(1);
    

    Assuming that the your score field is of type Integer, to solve this, please use the following method:

    public static void setScore(String operation) {
        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference scoreRef = rootRef.child("score");
        scoreRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Integer score = mutableData.getValue(Integer.class);
                if (score == null) {
                    return Transaction.success(mutableData);
                }
    
                if (operation.equals("increaseScore")) {
                    mutableData.setValue(score + 1);
                } else if (operation.equals("decreaseScore")){
                    mutableData.setValue(score - 1);
                }
    
                return Transaction.success(mutableData);
            }
    
            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
        });
    }
    

    For this, I recommend you definitely use transactions. You will avoid wrong results if users are trying to increase/decrease the score in the same time. So as a conclusion, call this method accordingly to your increase/decrease operation.

    This is how you can read it:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference scoreRef = rootRef.child("score");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Integer score = ds.getValue(Integer.class);
            Log.d("TAG", score + "");
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    scoreRef.addListenerForSingleValueEvent(eventListener);
    
    0 讨论(0)
  • 2020-11-22 10:33

    You need to first get the value of previous score and then add it with the current score and then update the final value in the firebase database.

    question_score.child("score").addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                String previousScore = dataSnapshot.getValue(String.class);
                                if (previousScore!=null){
                                    int finalScore = Integer.parseInt(previousScore) + current_score;
                                    question_score.child("score").setValue(String.valueOf(finalScore));
                                }
                            }
    
                            @Override
                            public void onCancelled(DatabaseError databaseError) {
    
                            }
                        });
    
    0 讨论(0)
  • 2020-11-22 10:52

    I think that previous score is a string in you code @DHANANJAY KUMAR and Strings cannot be added and also what is the meaning of String.class. I think It can be made

    int previousScore = dataSnapshot.getValue(Integer.class);
    

    if we can edit

    String.class
    

    to

    Integer.class
    

    or

    int.class
    

    Please Clarify

    0 讨论(0)
提交回复
热议问题